【问题标题】:Why is my password generation code not running?为什么我的密码生成代码没有运行?
【发布时间】:2022-01-23 07:12:28
【问题描述】:

我编写的这段代码应该会生成一个随机密码。以下是要求。

  1. 密码介于 1-128 个字符之间
  2. 密码包含大写、小写、数字和特殊字符,基于用户对询问他们是否希望密码包含这些字符的提示的响应。
  3. 当用户单击“生成密码”按钮时,它应该生成随机密码(基于提示响应)并在更改和文本区域框中显示密码

我不知道为什么我的 generatePassword() 函数代码没有运行。以下是 Chrome 开发者工具向我显示的错误以及 javascript 代码。

var password = "";
// characters object
var characters = {
  lowercase: "abcdefghijklmnopqrstuvwxyz",
  uppercase: "ABCDEFGHIJKLMNOPQRSTUVWXYZ",
  numeric: "0123456789",
  special: "!@#$%^&*()"
};

// Function to generate random number between 8 and 128 
var setPasswordLength = function() {
  var passwordLength = Math.floor(Math.random()*128)+8;
  return passwordLength;
};

// Function to set password characters
var setPasswordCharacters = function() {
  // when prompt answered input validated and character type selected
  var alphabet, numbers, special;
  while (alphabet === undefined) {
    var promptCase = window.prompt("Would you like your password to include UPPER case letters? Enter 'YES' or 'NO.'");
    switch (promptCase.toLowerCase()) {
      case "yes":
        alphabet = characters.lowercase + characters.uppercase;
        break;
      case "no":
        alphabet = characters.lowercase;
        break;
      default:
        window.alert("You need to provide a valid answer. Please try again.");
        break;
    }
  }
  while (numbers === undefined) {
    var promptNumeric = window.prompt("Would you like your password to include numbers? Enter 'YES' or 'NO.'");
    switch (promptNumeric.toLowerCase()) {
      case "yes":
        numbers = characters.numeric
        break;
      case "no":
        numbers = ""
        break;
      default:
        window.alert("You need to provide a valid answer. Please try again.");
        break;
    }
  }
  while (special === undefined) {
    var promptSpecial = window.prompt("Would you like your password to include special characters? Enter 'YES' or 'NO.'");
    switch (promptSpecial.toLowerCase()) {
      case "yes":
        special = characters.special
        break;
      case "no":
        special = ""
        break;
      default:
        window.alert("You need to provide a valid answer. Please try again.");
        break;
    }
  }
  // set password characters based on prompt responses
  password = alphabet + numbers + special;
  return;
};
// Function to shuffle password characters 
var shuffle = function() {
  var passwordArray = [];
  // convert password to an array 
  var passwordArray = password.split("");
  // randomly sort array items 
  passwordArray = array.sort(() => Math.random() - 0.5);
  // set password length from setPasswordLength()
  passwordArray.length = setPasswordLength()
  // convert passwordArray back to string 
  password = passwordArray.join("");
  return;
}

// FUNCTION TO GENERATE PASSWORD 
var generatePassword = function() {
  // prompt and ask for password inputs 
  setPasswordCharacters();
  // shuffle characters in answers to prompts 
  shuffle();
  // password displayed in an alert 
  window.alert("Your new password is " + password);
};

// Get references to the #generate element
var generateBtn = document.querySelector("#generate");

// Write password to the #password input
function writePassword() {
  generatePassword();
  var passwordText = document.querySelector("#password");

  passwordText.value = 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: default;
  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;
  }
}
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <meta http-equiv="X-UA-Compatible" content="ie=edge" />
  <title>Password Generator</title>
  <link rel="stylesheet" href="assets/css/style.css" />
</head>

<body>
  <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>
  <script src="assets/js/script.js"></script>
</body>

</html>

【问题讨论】:

  • 您的变量alphabet 仅在您的switch(promptCase) 语句内部 引入,但您的return alphabet 正试图引用它。尝试在 selectCase() 函数的顶部声明 var alphabet
  • @millhouse 用var 声明的变量具有函数作用域,而不是块作用域。
  • 这能回答你的问题吗? What is the scope of variables in JavaScript?
  • alphabetselectCase() 函数的局部变量,因此不能在函数之外引用它。另外,你永远不会打电话给selectCase()

标签: javascript html function password-generator


【解决方案1】:

您永远不会调用selectCase()selectNumeric()selectSpecial() 函数。而且它们定义的变量是这些函数的本地变量,因此您无法从setPasswordCharacters() 访问它们。

没有理由制作这些功能。只需使用while 循环不断提示,直到得到正确答案。

// Function to set password characters
var setPasswordCharacters = function() {
  // when prompt answered input validated and character type selected
  let alphabet, numbers, special;
  while (alphabet === undefined) {
    var promptCase = window.prompt("Would you like your password to include UPPER case letters? Enter 'YES' or 'NO.'");
    switch (promptCase.toLowerCase()) {
      case "yes":
        alphabet = characters.lowercase + characters.uppercase;
        break;
      case "no":
        alphabet = characters.lowercase;
        break;
      default:
        window.alert("You need to provide a valid answer. Please try again.");
        break;
    }
  }
  while (numbers === undefined) {
    var promptNumeric = window.prompt("Would you like your password to include numbers? Enter 'YES' or 'NO.'");
    switch (promptNumeric.toLowerCase()) {
      case "yes":
        numbers = characters.numeric
        break;
      case "no":
        numbers = ""
        break;
      default:
        window.alert("You need to provide a valid answer. Please try again.");
        break;
    }
  }
  while (special === undefined) {
    var promptSpecial = window.prompt("Would you like your password to include special characters? Enter 'YES' or 'NO.'");
    switch (promptSpecial.toLowerCase()) {
      case "yes":
        special = characters.special
        break;
      case "no":
        special = ""
        break;
      default:
        window.alert("You need to provide a valid answer. Please try again.");
        break;
    }
  }
  // set password characters based on prompt responses
  password = alphabet + numbers + special;
  return;
};

【讨论】:

  • 非常感谢!解决了一个问题!你知道为什么我的 shuffle 函数没有将密码字符串转换为数组,然后对项目进行洗牌,设置随机长度,然后再转换回字符串吗?我尝试将它嵌套在“generatePassword”函数中。
  • 我编辑了上面的代码,这样你就可以看到我做了什么。
  • 你不应该改变问题,现在没人能看到我在回答什么。
  • 你永远不会打电话给generatePassword()
  • 感谢您的提示。我将发布一个新问题
猜你喜欢
  • 2021-10-17
  • 2018-09-09
  • 1970-01-01
  • 2021-05-10
  • 2019-04-23
  • 2020-10-28
  • 2021-07-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多