【问题标题】:Random Password Generator showing undefined显示未定义的随机密码生成器
【发布时间】:2020-08-30 00:01:36
【问题描述】:

尝试为我所在的课程创建一个随机密码生成器,并且在大多数情况下一切正常。除了当我尝试生成密码时它最终只会说“未定义”这一事实。 JS如下。我们将不胜感激尽快提供帮助。

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);

【问题讨论】:

  • let random = Math.floor(Math.random().length); - 也许您打算使用 allChars 数组的长度?我不认为这条线正在做你期望它做的事情......

标签: javascript arrays for-loop


【解决方案1】:

起初,不是推送分割的字符数组,而是像这样连接它们:

allChars = allChars.concat(lowerArr);

下一步:

for 循环内的Math.floor() 函数是错误的。您必须将其与 allChars 数组的长度相结合,并将字符连接到密码变量:

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

【讨论】:

  • 现在肯定在正确的轨道上,我真的很感激。刚才我得到这样的东西 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 而不是随机的东西。一直试图让它工作几个小时,所以我的大脑有点炸了,对此我深表歉意。
  • 看看我的回答。
  • 非常感谢您。它现在终于可以工作了。字面上的上帝派来。
猜你喜欢
  • 2021-04-14
  • 2012-11-06
  • 2014-12-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-01-12
  • 1970-01-01
相关资源
最近更新 更多