本文介绍了循环,提示用户直到有效输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题:当年龄无效时如何连续提示用户(低于0,高于200,或者不是数字)?

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>


推荐答案

您可以使用<$ c $从while循环返回c> break 语句。例如:

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.");
}

这篇关于循环,提示用户直到有效输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-28 00:12