【问题标题】:Javascript Prompt Box LoopsJavascript 提示框循环
【发布时间】:2017-07-30 23:32:16
【问题描述】:
这段代码有问题,但我不知道它是什么。该页面无法正常工作或无法正常工作。我需要一个提示输入密码并将尝试次数限制为 3 次的代码。第三次尝试后,它需要有一个警告框。我还没有添加警报框之后的内容。
<script>
var attempts = 3;
var answer = prompt("Password: ");
while (attempts != 0)
{
if (answer == "Psycho")
{
document.write("These are pictures of my kitten and her things.");
}
else
{
answer = prompt("Password: ");
attempts--;
}
}
if (attempts = 0)
{
alert("Incorrect Password");
}
</script>
【问题讨论】:
标签:
javascript
loops
if-statement
while-loop
prompt
【解决方案1】:
有几个选项可以修复您的代码。
完成工作后您可以返回。
<script>
var attempts = 3;
var answer = prompt("Password: ");
while (attempts != 0)
{
if (answer == "Psycho")
{
document.write("These are pictures of my kitten and her things.");
return;
}
else
{
answer = prompt("Password: ");
attempts--;
}
}
if (attempts == 0)
{
alert("Incorrect Password");
}
</script>
或者,如果你失败了,我会早点回来
<script>
var attempts = 4;
var answer = prompt("Password: ");
while (attempts > 0 && answer != "Psycho")
{
answer = prompt("Password: ");
attempts--;
}
if (attempts == 0)
{
alert("Incorrect Password");
}
else
{
document.write("These are pictures of my kitten and her things.");
}
</script>
【解决方案2】:
您有几个问题。您应该在用户输入提示后检查条目。否则不会检查最后一个条目。下一个问题是您没有退出循环。另一个问题是 = 是赋值,所以如果你赋值为零,而不是检查它是否为零。
var attempts = 3;
while (attempts > 0) {
var answer = prompt("Password: ");
if (answer == "Psycho") {
document.write("These are pictures of my kitten and her things.");
break;
}
attempts--;
}
if (attempts == 0) {
alert("Incorrect Password");
}