简体   繁体   English

随机密码生成器显示未定义

[英]Random Password Generator showing undefined

Trying to create a random password generator for a class that I am in and for the most part got everything working just fine.尝试为我所在的 class 创建一个随机密码生成器,并且在大多数情况下一切正常。 Except for the fact that when i try to generate a password it ends up only saying "undefined".除了当我尝试生成密码时它最终只说“未定义”这一事实。 The JS is below. JS在下面。 Help as soon as possible would be greatly appreciated.尽快提供帮助将不胜感激。

const generateBtn = document.querySelector("#generate");


function writePassword() {
  const password = generatePassword();
  const passwordText = document.querySelector("#password");

  passwordText.value = password;
}


function generatePassword() {

  let lower = "abcdefghijklmnopqrstuvwxyz"
  let lowerArr = lower.split("");
  let upper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
  let upperArr = upper.split("");
  let num = "0123456789";
  let numArr = num.split("");
  let spec = "!@#$%^&*()_+?<>";
  let specArr = spec.split("");
  let allChars = [];

 
  let password = "";

  let pwlength = prompt("Choose password length: 8-128 characters.");

  if (pwlength < 8 || pwlength > 128) {
    alert("Password must be between defined length.")
    generatePassword()
  }
  if (confirm("Do you want lowercase characters?")) {
    allChars.push(lowerArr);
  }
  if (confirm("Do you want uppercase characters?")) {
    allChars.push(upperArr);
  }
  if (confirm("Do you wamt numeric characters?")) {
    allChars.push(numArr);
  }
  if (confirm("Do you want special characters?")) {
    allChars.push(specArr);
  }
  if (allChars.length === 0) {
    alert("Minimum of one type of character must be chosen");
    generatePassword()
  }
  for (let i = 0; i < pwlength; ++i) {
    let random = Math.floor(Math.random().length);
    password = allChars[random];
  }

  return password;
}



generateBtn.addEventListener("click", writePassword);

At first, instead of pushing the splitted character arrays, just concat them like:首先,不是推送拆分字符 arrays,而是像这样连接它们:

allChars = allChars.concat(lowerArr);

Next:下一个:

The Math.floor() function inside the for loop is wrong. for 循环里面的Math.floor() function 是错误的。 You have to combine it with the length of the allChars Array and concatinate the characters to the password variable:您必须将它与allChars数组的长度结合起来,并将字符连接到密码变量:

for (let i = 0; i < pwlength; ++i) {
    let random = Math.floor(Math.random() * Math.floor(allChars.length));
    password += allChars[random];
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM