我想知道如果输入成功你将如何离开for循环,用户将有3次尝试输入一个大于0的数字。它为他们工作不成功但它仍然让我输入值3次即使一个输入正确的数字。
for (var attempts = 3; attempts--;) {
var input = window.prompt("Please enter a number");
if ( input < 0) {
document.write("Try Again");
}
}
document.write("Grand");
答案 0 :(得分:1)
您可以使用break
语句留下循环。
for (var attempts = 3; attempts > 0; attempts--) {
var input = window.prompt("Please enter a number");
if ( input < 0) {
if(attempts > 1){
document.write("Try Again");
}else{
document.write("No more attempts!");
}
}else{
break;
}
}
答案 1 :(得分:1)
以下是您的代码存在的问题:
else
声明。如果他们没有输入正确的代码,则无法有条件地处理任何 else 。它总是处理&#34; Grand&#34;输出无论输出如何。< 0
的条件不是你想要的。如果他们输入0
,它仍会通过支票并说“再试一次”#34; else
语句中添加中断。试试这个:
<script>
for (var attempts = 1; attempts <= 3; attempts++) {
var input = window.prompt("Please enter a number");
if (input <= 0) {
if (attempts == 3) {
//this is the 3rd failure
document.write("You have failed 3 times!");
break;
} else {
//this is for the 1st and second failures
document.write("Try Again<br>");
}
} else {
document.write("Grand");
break;
}
}
</script>
答案 2 :(得分:0)
有很多方法可以做到,这里有一个:
var attempts = 3, valid_input = false, input;
while (attempts > 0 && valid_input === false) {
input = parseInt(window.prompt("Please enter a number"), 10);
if (input <= 0) {
alert("Try Again");
} else {
valid_input = true;
}
}
if (valid_input === true) {
document.write("Grand");
} else {
document.write("Failed 3 times");
}