Javascript:循环结束后的警报消息
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Javascript:循环结束后的警报消息相关的知识,希望对你有一定的参考价值。
这是一个简单的学校登录练习。这是为了给你3次登录尝试。我想在循环停止后(使用三次尝试)这样做,它会提醒用户他没有剩余的尝试,他的帐户将被阻止。
就像是:
alert("You don't have any attempts left. Your account is now blocked);
这是我制作的循环:
var tries;
for (tries = 2; tries !== -1; tries--) {
let User = prompt("Enter your username:");
let Pass = prompt("Enter your password:");
if (User === "hello" && Pass === "world") {
alert("Welcome.");
break;
} else {
alert("Incorrect username and/or password. You have " + tries + " attempt(s) left.");
}
}
提前致谢。
答案
你在哪里非常接近。我想这就是你想要的。
var tries;
for (tries = 2; tries >= 0; tries--) {
let User = prompt("Enter your username:");
let Pass = prompt("Enter your password:");
if (User === "hello" && Pass === "world") {
alert("Welcome.");
break;
} else if (tries == 0) {
alert("You don't have any attempts left. Your account is now blocked");
} else {
alert("Incorrect username and/or password. You have " + tries + " attempt(s) left.");
}
}
另一答案
你可以递归地实现这一点。每次输入错误的用户名或密码时,只需减少尝试次数。
var TRIES = 3;
function ask() {
let User = prompt("Enter your username:");
let Pass = prompt("Enter your password:");
if (User === "hello" && Pass === "world") {
return alert("Welcome.");
}
if (TRIES > 0) {
alert("Incorrect username and/or password. You have " + TRIES + " attempt(s) left.");
TRIES -= 1;
ask()
} else {
alert("You don't have any attempts left. Your account is now blocked");
}
}
ask()
另一答案
var tries;
for (tries = 0; tries < 3; tries++) {
let User = prompt("Enter your username:");
let Pass = prompt("Enter your password:");
if (User === "hello" && Pass === "world") {
alert("Welcome.");
break;
} else {
alert("Incorrect username and/or password. You have " + tries + " attempt(s) left.");
}
if(tries == 2)
{
alert("You don't have any attempts left. Your account is now blocked);
}
}
另一答案
let tries = 0;
for (tries = 3; tries-->0;) {
let User = prompt("Enter your username:");
let Pass = prompt("Enter your password:");
if (User === "hello" && Pass === "world") {
break;
}
if (tries>0) {
alert("Incorrect username and/or password. You have " + tries + " attempt(s) left.");
}
}
if (tries<0) {
alert("You don't have any attempts left. Your account is now blocked");
} else {
alert("Welcome.");
}
另一答案
也许您可以通过执行以下操作来实现此目的:
for (var attemptsRemaining = 3; attemptsRemaining > 0; attemptsRemaining--) {
let User = prompt("Enter your username:");
let Pass = prompt("Enter your password:");
if (User === "hello" && Pass === "world") {
alert("Welcome.");
break;
} else if(attemptsRemaining <= 1) {
alert("To many failed attempts. Your account is now blocked.");
}
else {
alert("Incorrect username and/or password. You have " + (attemptsRemaining - 1) + " attempt(s) left.");
}
}
}
以上是关于Javascript:循环结束后的警报消息的主要内容,如果未能解决你的问题,请参考以下文章