JS 确认信息

JS Confirm Message

我是 JavaScript 的新手,目前正在为一个项目创建密码生成器。我 运行 遇到一个问题,当用户收到 confirm 消息提示 select 他们理想的密码标准时。如果他们至少没有选择一个选项,我想 return 通过 loop 功能向 window 发送 alert 消息。这是我目前所拥有的。

// function: when you click on generate button it prompts messages to select password criteria. 
var generateBtnPrompt = function () {
    var confirmNumber = confirm("Click 'OK' to generate numbers in your password");
    var confirmLowerCase = confirm("Click 'OK' to generate lowerCase characters in your password");
    var confirmUpperCase = confirm("Click 'OK' to generate upperCase characters in your password");
    var confirmSymbols = confirm("Click 'OK' to generate symbols characters in your password");
    //parseInt convert a string into an integer
    var charLength = parseInt(prompt("How many characters would you like your password to be? Please choose a number from (8-128)"));
};

您可以使用 Logical OR 运算符 (||) 来检查至少有一个变量为真。

MDN Web Docs:
The logical OR (||) operator (logical disjunction) for a set of operands is true if and only if one or more of its operands is true.

recursion重新运行函数如果none的变量为真。

像这样:

if (!(confirmNumber || confirmLowerCase || confirmUpperCase)) {
  alert("You need to pick at least one!");
  return generateBtnPrompt()
}

完整代码:

var generateBtnPrompt = function () {
    var confirmNumber = confirm("Click 'OK' to generate numbers in your password");
    var confirmLowerCase = confirm("Click 'OK' to generate lowerCase characters in your password");
    var confirmUpperCase = confirm("Click 'OK' to generate upperCase characters in your password");
    var confirmSymbols = confirm("Click 'OK' to generate symbols characters in your password");
    
    if (!(confirmNumber || confirmLowerCase || confirmUpperCase)) {
      alert("You need to pick at least one!");
      return generateBtnPrompt()
    }
    
    var charLength = parseInt(prompt("How many characters would you like your password to be? Please choose a number from (8-128)"));
};

generateBtnPrompt()