【问题标题】:Random password generator returning undefined along with generated password (javascript)随机密码生成器返回未定义以及生成的密码(javascript)
【发布时间】:2021-04-14 05:33:17
【问题描述】:

示例输出

undefined@pz#$n%s!@$@p!y
  • userInput 提示用户输入他们想要的密码字符。

  • generatePassword 获取用户条件并将其添加到数组中,然后从数组中的随机字符串中进行选择。

我很难弄清楚为什么 `undefined 会与密码一起返回。

var generateBtn = document.querySelector("#generate");
var upperCaseLetters = ["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"];
var lowerCaseLetters = ["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"];
var numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
var symbols = ["!", "@", "#", "$", "%"];
var pw = [];
// Write password to the #password input
function writePassword() {
  var pwCriteria = getUserInput();
  //console.log(pwCriteria);
  var password = generatePassword(pwCriteria);
  //console.log(password);
  var passwordText = document.querySelector("#password");

  //Math.random();

  passwordText.value = password;

}

function generatePassword(criteria) {
  var pw = [];
  if (criteria.lowerCase) {
    for (var i = 0; i <= criteria.length; i++) {
      var randomIndex = Math.floor(Math.random() * lowerCaseLetters.length);
      var randomChar = lowerCaseLetters[randomIndex];
      console.log(randomIndex);
      console.log(randomChar);
      pw = pw + randomChar;
    }
  }

  if (criteria.upperCase) {
    for (var i = 0; i <= criteria.length; i++) {
      var randomIndex2 = Math.floor(Math.random() * upperCaseLetters.length);
      var randomChar = upperCaseLetters[randomIndex2];
      pw = pw + randomChar;
    }
  }
  if (criteria.specialChar) {
    for (var i = 0; i <= criteria.length; i++) {
      var randomIndex3 = Math.floor(Math.random() * symbols.length);
      var randomChar = symbols[randomIndex3];
      pw = pw + randomChar;
    }
  }

  if (criteria.num) {
    for (var i = 0; i <= criteria.length; i++) {
      var randomIndex5 = Math.floor(Math.random() * numbers.length);
      var randomChar = numbers[randomIndex5];
      pw = pw + randomChar;
    }
  }

  if (criteria.lowerCase === false && criteria.upperCase === false && criteria.specialChar === false && criteria.num === false) {
    alert("You must choose at least one character type to put in your password.")
  }

  for (var i = 0; i <= criteria.length - 1; i++) {
    var random = Math.floor(Math.random() * pw.length);
    var str = pw[random];
    var newPw = newPw + str;
  }

  return newPw;

}

function getUserInput() {
  var length = parseInt(prompt("How many characters would you like your password to be? (Between 8 and 128)"));
  if (length >= 8 && length <= 128) {} else {
    alert("The password has to be between 8 and 128 characters");
    return getUserInput();
  }
  var lowerCase = confirm("Would you like lowercase characters in your password?");
  var upperCase = confirm("Would you like uppercase characters in your password?");
  var specialChar = confirm("Would you like special characters in your password?");
  var num = confirm("Would you like your password to have numbers in it?");
  return {
    length: parseInt(length),
    lowerCase,
    upperCase,
    specialChar,
    num,
  }
}
// Add event listener to generate button
generateBtn.addEventListener("click", writePassword);
&lt;input id="password"/&gt;&lt;button class="button" id="generate"&gt;Generate&lt;/button&gt;

【问题讨论】:

  • var newPw = newPw + str; 先初始化newPw,不要在那里使用var
  • 另外,如果你要向它添加随机字符,为什么 pw 用一个空数组初始化
  • 投票结束为 不可重现或由拼写错误引起。虽然类似的问题可能是这里的主题,但这个问题的解决方式不太可能帮助未来的读者。
  • 推送到pw并在显示之前打乱数组
  • 也可以写成someBoolean === false !someBoolean

标签: javascript function passwords undefined


【解决方案1】:

推送到 pw 或更好:map

我只需要重写这个

我试图在保持可读性的同时尽可能干燥

我没有触摸输入创建

const generateBtn = document.getElementById("generate"); // IDs are unique, no need for querySelector
const passwordText = document.getElementById("password");
const getRnd = arr => arr[Math.floor(Math.random() * arr.length)]
const letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
const upperCaseLetters = [...letters]; // spread to array
const lowerCaseLetters = [...letters.toLowerCase()];
const numbers = [..."0123456789"];
const symbols = [..."!@#$%"];
let pw = [];

generateBtn.addEventListener("click", function() {
  const pwCriteria = getUserInput();
  passwordText.value = generatePassword(pwCriteria);
});


function generatePassword(criteria) {
  if (!criteria.lowerCase &&
    !criteria.upperCase &&
    !criteria.specialChar &&
    !criteria.num) {
    alert("You must choose at least one character type to put in your password.")
    return;
  }
  const lengthArr = [...Array(criteria.length).keys()]; // create an array just for the map's sake

  if (criteria.lowerCase) pw = pw.concat(lengthArr.map(num => getRnd(lowerCaseLetters)));
  if (criteria.upperCase) pw = pw.concat(lengthArr.map(num => getRnd(upperCaseLetters)));
  if (criteria.specialChar) pw = pw.concat(lengthArr.map(num => getRnd(symbols)));
  if (criteria.num) pw = pw.concat(lengthArr.map(num => getRnd(numbers)));
  console.log(pw)
  return pw // shuffle from https://stackoverflow.com/a/46545530/295783
    .map((a) => ({
      sort: Math.random(),
      value: a
    }))
    .sort((a, b) => a.sort - b.sort)
    .map((a) => a.value)
    .join("")
    .slice(0,criteria.length);

}

function getUserInput() {
  var length = parseInt(prompt("How many characters would you like your password to be? (Between 8 and 128)"));
  if (length >= 8 && length <= 128) {} else {
    alert("The password has to be between 8 and 128 characters");
    return getUserInput();
  }
  var lowerCase = confirm("Would you like lowercase characters in your password?");
  var upperCase = confirm("Would you like uppercase characters in your password?");
  var specialChar = confirm("Would you like special characters in your password?");
  var num = confirm("Would you like your password to have numbers in it?");
  return {
    length: parseInt(length),
    lowerCase,
    upperCase,
    specialChar,
    num,
  }
}
&lt;input id="password" /&gt;&lt;button class="button" id="generate"&gt;Generate&lt;/button&gt;

【讨论】:

    猜你喜欢
    • 2020-05-11
    • 2022-09-23
    • 1970-01-01
    • 1970-01-01
    • 2012-11-06
    • 1970-01-01
    • 2010-09-08
    相关资源
    最近更新 更多