#javascript #arrays #object
#javascript #массивы #объект
Вопрос:
Новичок в javascript имеет проект генератора паролей
Я пытаюсь получить доступ к объекту PasswordInfo вне функции generatePasswordInfo. Я хочу передать длину пароля, чтобы я мог сгенерировать случайный символ для длины запрошенного пароля.
Я фиксирую длину пароля с помощью переменной getpasswordLength, сохраняю ее в PasswordInfo. Я думаю, что именно здесь у меня возникла проблема с возвратом значения в PasswordInfo.
Я беру функцию generatePasswordInfo, которая содержит PasswordInfo, и сохраняю ее в переменной passwordIncludes . Затем я повторяю, хотя длина пароля включает в себя захват случайного символа для каждого индекса. Затем вставьте это в пустой массив createdPassword.
// numbers array
var numbersChar = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"];
//lowercase array
var lowerCaseChar = [
"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"
];
//uppcase array
var upperCaseChar = [
"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"
];
// special char array
var specialChar = [
"@", "%", " ", "\", "/", "'", "!", "#", "$", "^", "?", ":", ",", ")", "(", "}", "{", "]", "[", "~", "-", "_", "."
];
// Assignment code here
function generatePasswordInfo() {
var getPasswordLength = parseInt(prompt("Choose number of characters for your password."));
if(getPasswordLength < 8 ) {
alert("A minimum number of 8 characters requried.");
generatePassword();
}
if(getPasswordLength > 128 ) {
alert("A Maximum number of 128 characters requried.");
generatePassword();
}
if (isNaN(getPasswordLength)) {
alert("Invalid input. Please insert a number.");
generatePassword();
}
//Confirm including lowercase letters
var includeLowerCase = window.confirm("Click Ok to include lowercase characters");
//Confirm including uppercase letter
var includeUpperCase = window.confirm("click Ok to include uppercase characters");
//Confirm including numbers
var includeNumbers = window.confirm("click Ok to include numbers");
//Confirm including special characters
var includespecial = window.confirm("click Ok to include special characters");
if (!includeLowerCase amp;amp; !includeUpperCase amp;amp; !includeNumbers amp;amp; !includespecial) {
alert("Minimum of 1 character type needed.");
return;
}
//stores password Info in object
var passwordInfo = {
passwordLength: getPasswordLength,
includeLowerCase: includeLowerCase,
includeUpperCase: includeUpperCase,
includeNumbers: includeNumbers,
includespecial: includespecial
};
return passwordInfo;
}
// Get a random character from an array
function getRandomChar(arr) {
var randomChar = Math.floor(Math.random() * arr.length);
var selectedChar = arr[randomChar];
return selectedChar;
}
function generatePassword() {
// passwordInfo object
var passwordIncludes = generatePasswordInfo();
//store created password
var createdPassword = [];
// Array to store types of characters to include in password
var availableCharacters = [];
// adds array of lower characters to array of available characters
if(passwordIncludes.includeLowerCase) {
availableCharacters = availableCharacters.concat(lowerCaseChar);
}
// adds array of upper characters to array of available characters
if(passwordIncludes.includeUpperCase) {
availableCharacters = availableCharacters.concat(upperCaseChar);
}
// adds array of numbers to array of available characters
if(passwordIncludes.includeNumbers) {
availableCharacters = availableCharacters.concat(numbersChar);
}
// adds array of special characters to array of available characters
if(passwordIncludes.includespecial) {
availableCharacters = availableCharacters.concat(specialChar);
}
// Iterate through the password length, get random index from the array of available characters
for (var i = 0; i < passwordIncludes.length; i ) {
availableCharacters = getRandomChar(availableCharacters);
// add characters to password array
createdPassword.push(availableCharacters);
}
return createdPassword.join("");
}
// Get references to the #generate element
var generateBtn = document.querySelector("#generate");
// Write password to the #password input
function writePassword() {
var password = generatePassword();
var passwordText = document.querySelector("#password");
passwordText.value = password;
}
// Add event listener to generate button
generateBtn.addEventListener("click", writePassword);
вот jsfiddle
https://jsfiddle.net/v74aqxtL /
Комментарии:
1.
passwordInfo
это объект со строками в качестве ключей и функциями в качестве значений, эти функции не вызываются.
Ответ №1:
Есть 2 проблемы с вашим кодом
- При выполнении цикла для генерации нужного количества символов, которые вы делаете
for (var i = 0; i < passwordIncludes.length; i ) {
, когда это должно сказатьfor (var i = 0; i < passwordIncludes.passwordLength; i ) {
- Вы переопределяете доступные символы с
availableCharacters = getRandomChar(availableCharacters);
помощью make it something likevar c = getRandomChar(availableCharacters)
и объединяетеc
в сгенерированный пароль
// numbers array
var numbersChar = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"];
//lowercase array
var lowerCaseChar = [
"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"
];
//uppcase array
var upperCaseChar = [
"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"
];
// special char array
var specialChar = [
"@", "%", " ", "\", "/", "'", "!", "#", "$", "^", "?", ":", ",", ")", "(", "}", "{", "]", "[", "~", "-", "_", "."
];
// Assignment code here
function generatePasswordInfo() {
var getPasswordLength = parseInt(prompt("Choose number of characters for your password."));
if(getPasswordLength < 8 ) {
alert("A minimum number of 8 characters requried.");
generatePassword();
}
if(getPasswordLength > 128 ) {
alert("A Maximum number of 128 characters requried.");
generatePassword();
}
if (isNaN(getPasswordLength)) {
alert("Invalid input. Please insert a number.");
generatePassword();
}
//Confirm including lowercase letters
var includeLowerCase = window.confirm("Click Ok to include lowercase characters");
//Confirm including uppercase letter
var includeUpperCase = window.confirm("click Ok to include uppercase characters");
//Confirm including numbers
var includeNumbers = window.confirm("click Ok to include numbers");
//Confirm including special characters
var includespecial = window.confirm("click Ok to include special characters");
if (!includeLowerCase amp;amp; !includeUpperCase amp;amp; !includeNumbers amp;amp; !includespecial) {
alert("Minimum of 1 character type needed.");
return;
}
//stores password Info in object
var passwordInfo = {
passwordLength: getPasswordLength,
includeLowerCase: includeLowerCase,
includeUpperCase: includeUpperCase,
includeNumbers: includeNumbers,
includespecial: includespecial
};
return passwordInfo;
}
// Get a random character from an array
function getRandomChar(arr) {
var randomChar = Math.floor(Math.random() * arr.length);
var selectedChar = arr[randomChar];
return selectedChar;
}
function generatePassword() {
// passwordInfo object
var passwordIncludes = generatePasswordInfo();
//store created password
var createdPassword = [];
// Array to store types of characters to include in password
var availableCharacters = [];
// adds array of lower characters to array of available characters
if(passwordIncludes.includeLowerCase) {
availableCharacters = availableCharacters.concat(lowerCaseChar);
}
// adds array of upper characters to array of available characters
if(passwordIncludes.includeUpperCase) {
availableCharacters = availableCharacters.concat(upperCaseChar);
}
// adds array of numbers to array of available characters
if(passwordIncludes.includeNumbers) {
availableCharacters = availableCharacters.concat(numbersChar);
}
// adds array of special characters to array of available characters
if(passwordIncludes.includespecial) {
availableCharacters = availableCharacters.concat(specialChar);
}
// Iterate through the password length, get random index from the array of available characters
for (var i = 0; i < passwordIncludes.passwordLength; i ) {
var c = getRandomChar(availableCharacters);
// add characters to password array
createdPassword.push(c);
}
return createdPassword.join("");
}
// Get references to the #generate element
var generateBtn = document.querySelector("#generate");
// Write password to the #password input
function writePassword() {
var password = generatePassword();
var passwordText = document.querySelector("#password");
passwordText.innerHTML = password;
}
// Add event listener to generate button
generateBtn.addEventListener("click", writePassword);
*,
*::before,
*::after {
box-sizing: border-box;
}
html,
body,
.wrapper {
height: 100%;
margin: 0;
padding: 0;
}
body {
font-family: sans-serif;
background-color: #f9fbfd;
}
.wrapper {
padding-top: 30px;
padding-left: 20px;
padding-right: 20px;
}
header {
text-align: center;
padding: 20px;
padding-top: 0px;
color: hsl(206, 17%, 28%);
}
.card {
background-color: hsl(0, 0%, 100%);
border-radius: 5px;
border-width: 1px;
box-shadow: rgba(0, 0, 0, 0.15) 0px 2px 8px 0px;
color: hsl(206, 17%, 28%);
font-size: 18px;
margin: 0 auto;
max-width: 800px;
padding: 30px 40px;
}
.card-header::after {
content: " ";
display: block;
width: 100%;
background: #e7e9eb;
height: 2px;
}
.card-body {
min-height: 100px;
}
.card-footer {
text-align: center;
}
.card-footer::before {
content: " ";
display: block;
width: 100%;
background: #e7e9eb;
height: 2px;
}
.card-footer::after {
content: " ";
display: block;
clear: both;
}
.btn {
border: none;
background-color: hsl(360, 91%, 36%);
border-radius: 25px;
box-shadow: rgba(0, 0, 0, 0.1) 0px 1px 6px 0px rgba(0, 0, 0, 0.2) 0px 1px 1px
0px;
color: hsl(0, 0%, 100%);
display: inline-block;
font-size: 22px;
line-height: 22px;
margin: 16px 16px 16px 20px;
padding: 14px 34px;
text-align: center;
cursor: pointer;
}
button[disabled] {
cursor: defau<
background: #c0c7cf;
}
.float-right {
float: right;
}
#password {
-webkit-appearance: none;
-moz-appearance: none;
appearance: none;
border: none;
display: block;
width: 100%;
padding-top: 15px;
padding-left: 15px;
padding-right: 15px;
padding-bottom: 85px;
font-size: 1.2rem;
text-align: center;
margin-top: 10px;
margin-bottom: 10px;
border: 2px dashed #c0c7cf;
border-radius: 6px;
resize: none;
overflow: hidden;
}
@media (max-width: 690px) {
.btn {
font-size: 1rem;
margin: 16px 0px 0px 0px;
padding: 10px 15px;
}
#password {
font-size: 1rem;
}
}
@media (max-width: 500px) {
.btn {
font-size: 0.8rem;
}
}
<div class="wrapper">
<header>
<h1>Password Generator</h1>
</header>
<div class="card">
<div class="card-header">
<h2>Generate a Password</h2>
</div>
<div class="card-body">
<textarea
readonly
id="password"
placeholder="Your Secure Password"
aria-label="Generated Password"
></textarea>
</div>
<div class="card-footer">
<button id="generate" class="btn">Generate Password</button>
</div>
</div>
</div>
Ответ №2:
Я думаю, что вы на самом деле (/ первая) проблема в том, что вы должны ссылаться:
passwordIncludes.passwordLength
Вместо того , чтобы:
passwordIncludes.length
В вашем цикле «для»:
for (var i = 0; i < passwordIncludes.length; i ) {