JavaScript,一个询问特定答案的循环

时间:2014-05-14 20:44:24

标签: javascript

我希望用户输入1-100之间的数字,直到用户输入有效数字,循环将继续说“输入无效”。

我的代码如下。我哪里出错了?

// Initialize var userGuess
var userGuess;

// I want to make the prompt keep asking a number between 1-100, if it doesn't satisfy the requirement, it will keep asking
for (var valid = false; valid == true;) {
    userGuess = prompt("Guess a number");
    if ((userGuess >= 1) && (userGuess <= 100)) {
        valid = true;
    } else {
        valid = false;
        console.log("That number is invalid! Please enter a number between 1-100");
    }
}

2 个答案:

答案 0 :(得分:5)

// Initialize var userGuess
var userGuess;

// I want to make the prompt keep asking a number between 1-100, if it doesn't satisfy the requirement, it will keep asking
var valid = false;
while(!valid){
    userGuess = prompt("Guess a number");
    if ((userGuess >= 1) && (userGuess <= 100)) {
        valid = true;
    } else {
        console.log("That number is invalid! Please enter a number between 1-100");
    }
}


// Initialize var userGuess
var userGuess;

使用for循环

// I want to make the prompt keep asking a number between 1-100, if it doesn't satisfy the requirement, it will keep asking
for(var valid = false; !valid){
    userGuess = prompt("Guess a number");
    if ((userGuess >= 1) && (userGuess <= 100)) {
        valid = true;
    } else {
        console.log("That number is invalid! Please enter a number between 1-100");
    }
}

答案 1 :(得分:1)

就个人而言,在您尝试捕获有效用户输入的场景中,我更倾向于使用递归函数调用。

function userValue(){
    var guess = prompt("Guess a number")
    if(guess > 0 && guess <= 100){
         return guess; 
    }

    return userValue();
}

var value = userValue();

我用这种方法做了一些应用程序。这是你的电话。

w ^