密码生成器问题

我的作业代码应该提示用户输入密码长度和字符类型。出现提示时,我希望用户最多可以输入 3 个答案(即“大写、小写、特殊”),但是当我运行它时,它只接受一个答案。这是我的代码,请帮助:


var length = Number(prompt("Enter a password length between 8 and 128")),

  charType = prompt("Enter up to 3 character types: special, numeric, uppercase, lowercase."),


  password = generatePassword();

document.getElementById("display").value = password;

document.getElementById('copy-btn').addEventListener('click', copyPassword);


function generatePassword() {

  var charSets = {

    lowercase: 'abcdefghijklmnopqrstuvwxyz',

    uppercase: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ',

    numeric: '0123456789',

    special: ' !"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'

  };

  var charSet = charSets[charType.toLowerCase()] || charSets.lowercase;

  var retVal = "";

  for (var i = 0; i < length; i++) {

    retVal += charSet.charAt(Math.floor(Math.random() * charSet.length));

  }

  return retVal;

}


function copyPassword() {

  document.getElementById("display").select();

  document.execCommand("Copy");

  alert("Password copied to clipboard!");

}


富国沪深
浏览 59回答 1
1回答

慕妹3242003

您可以将输入拆分为逗号和多个空格或仅多个空格(使用Phil建议的正则表达式)并遍历每个部分,将所有指定的字符集连接在一起。var length = Number(prompt("Enter a password length between 8 and 128")),&nbsp; charType = prompt("Enter up to 3 character types: special, numeric, uppercase, lowercase."),&nbsp; password = generatePassword();document.getElementById("display").value = password;document.getElementById('copy-btn').addEventListener('click', copyPassword);function generatePassword() {&nbsp; var charSets = {&nbsp; &nbsp; lowercase: 'abcdefghijklmnopqrstuvwxyz',&nbsp; &nbsp; uppercase: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ',&nbsp; &nbsp; numeric: '0123456789',&nbsp; &nbsp; special: ' !"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'&nbsp; };&nbsp; var charSet = charType?&nbsp;&nbsp; &nbsp; charType.split(/,\s*|\s+/).reduce((acc,curr)=>acc + charSets[curr.trim().toLowerCase()],"")&nbsp;&nbsp; &nbsp; : charSets.lowercase;&nbsp; var retVal = "";&nbsp; for (var i = 0; i < length; i++) {&nbsp; &nbsp; retVal += charSet.charAt(Math.floor(Math.random() * charSet.length));&nbsp; }&nbsp; return retVal;}function copyPassword() {&nbsp; document.getElementById("display").select();&nbsp; document.execCommand("Copy");&nbsp; alert("Password copied to clipboard!");}<textarea id="display"></textarea><button id="copy-btn">Copy<button>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript