enter a password if 3 time wrong attempt 如果用户输入了两次错误的密码,但第三次能够提供正确的密码

enter a password if 3 time wrong attempt If the user enters two incorrect passwords, but was able to provide the correct password for the 3rd time

任何人都可以帮我解决这个我刚开始学习 JS 创建一个程序,如果用户输入了三次错误密码,该程序将退出//如果用户输入了两次错误密码,但第三次能够提供正确的密码,请将计数器变量重置为 0

//3 密码输入错误, add alert("您的账号已被封禁!"); 这是我到目前为止所做的

const userPass = "Password123";
let inputPass = prompt("Please enter your password:");
let counter = 0;

while (inputPass != userPass) {
    inputPass = prompt("Please enter your password:");
}

console.log("Thank you for providing the right password!");
const userPass = "Password123";
let inputPass = prompt("Please enter your password:");
let counter = 0;

while (inputPass != userPass && counter <3) {
    inputPass = prompt("Please enter your password:");
    counter++
}

if(counter < 3) console.log("Thank you for providing the right password!");
else console.log("Your account is blocked")

这是您要找的吗? https://jsfiddle.net/8e2k0ymh/

const userPass = 'Password123';
let inputPass = prompt('Please enter your password:');
let counter = 0;

while (inputPass != userPass && ++counter < 3) {
    inputPass = prompt('Please enter your password:');
}
if (counter == 3) {
    alert('Your account has been blocked!');
} else {
    alert('Thank you for providing the right password!');
}

我会在提交密码后 运行 一个 if 语句来检查密码是否正确。如果不正确添加到计数器并检查计数器是否等于 3.

if (inputPass != userPass) {
  counter++;
  if (counter >= 3) {
    inputPass = prompt('You have been blocked!');
  }
}

这里有解决方案:

const userPass = 'Password123'

let inputPass = prompt('Please enter your password:')
let counter = 1
const MAX_ATTEMPS = 3

while (inputPass != userPass) {
  if (counter < 3) inputPass = prompt('Please enter your password:')
  else {
    alert('Account has been blocked')
    break
  }

  counter++
}

counter = 1

console.log('Thank you for providing the right password!')

请注意,counter 已从 0 修改为 1,并添加了一个新常量 MAX_ATTEMPS

还添加了一个 if 语句来处理 while 循环体中的 3 次尝试。