问题
Question: How to continuously prompt user when age is invalid (below 0 above 200, or not-a-number)?
var userAge = prompt("Please enter your age");
while (isNaN(userAge)){
alert("That's not a number, please retry.");
var userAge = prompt("Please re-enter your age.");
}
if (userAge == 0){
alert("So you're a baby!");
}
while( userAge < 0 || userAge >= 200){
alert("I think you may be lying about your age.");
var userAge = prompt("Please re-enter your age, don't lie this time.");
{continue}
}
if (userAge > 0 || userAge < 200){
alert("That's a good age.");
}
</script>
回答1:
You can return from while loop with break
statement. For example:
var userAge = prompt("Please enter your age");
while (true) {
if (isNaN(userAge)) {
alert("That's not a number, please retry.");
} else if (userAge < 0 || userAge >= 200) {
alert("I think you may be lying about your age.");
} else {
break;
}
var userAge = prompt("Please re-enter your age.");
}
if (userAge == 0) {
alert("So you're a baby!");
} else {
alert("That's a good age.");
}
来源:https://stackoverflow.com/questions/35044961/loop-that-prompts-user-until-valid-input