【问题标题】:How to return to the same condition if the password is wrong twice两次密码错误如何返回相同状态
【发布时间】:2022-01-15 21:58:23
【问题描述】:

当你输入错误的密码时,会显示错误的警报,但当你第二次输入时,它只是让你在现场。

var password = "Password123";
          var pass = window.prompt("Enter password: ");
          if (pass == sifra) {
            alert("Correct");
          } else {
            var pass = window.prompt("Incorrect password: ");
          }

【问题讨论】:

    标签: javascript loops if-statement passwords


    【解决方案1】:

    发生这种情况是因为第二次它只是输入但不验证密码,如果你想验证密码直到它正确,你可以尝试添加一个循环

    var pass = window.prompt("Enter password: ");
    while (pass !== sifra) {
      pass = window.prompt("incorrenct password try again: ");
    }
    // reaches here only when password is corrent
    

    【讨论】:

      【解决方案2】:

      您导致您的代码在第二次提示后没有检查。在这种情况下,您应该以recursion 的方式编写代码。当密码检查失败时,它应该一次又一次地开始相同的过程,直到它通过为止。

      // fn: verify the password
      function verifyPassword(pass) {
        if (pass === "sifra") {
          alert("Correct");
        } else {
          // prompt the password again if it's incorrect
          promptPassword("Incorrect password: ");
        }
      }
      
      // fn: promoting the password
      function promptPassword(msg = "Enter password:") {
        var pass = window.prompt(`${msg} `);
      
        // verify the password
        verifyPassword(pass);
      }
      
      promptPassword();

      【讨论】:

      • 比你不需要 var password = "Password123";
      • 当然,我只是想保留您的详细信息,原样
      • 好的,谢谢
      猜你喜欢
      • 2012-03-14
      • 1970-01-01
      • 1970-01-01
      • 2016-02-07
      • 2021-08-12
      • 1970-01-01
      • 1970-01-01
      • 2020-05-15
      • 2020-04-10
      相关资源
      最近更新 更多