这个JS代码缺少什么来使它循环

时间:2014-09-12 00:37:26

标签: javascript

当提示输入错误时,这个基本代码缺少什么使它循环?

var userChoice = prompt("Do you choose rock, paper or scissors?");
var error = "Error. You should input rock, paper or scissors!";
var inputAgain = "Do you choose rock, paper or scissors?";
    if(userChoice!=="rock") {
        if(userChoice!=="paper") {
            if(userChoice!=="scissors") {
                confirm(error);
                userChoice = prompt("Do you choose rock, paper or scissors?");
            }
        }
    }

4 个答案:

答案 0 :(得分:1)

var requiredValues = ["rock","paper","scissors"];
while(requiredValues.indexOf(prompt("Do you choose rock, paper or scissors?"))<0){
    alert("Error. You should input rock, paper or scissors!");
}

答案 1 :(得分:0)

您的代码需要一个循环,以便可以继续询问和回答问题。

var options = ["rock","paper","scissors"],
    userChoice;

while (true) {
    userChoice = prompt("Do you choose rock, paper or scissors?");

    // stop asking if answer is valid
    if (options.indexOf(userChoice.trim().toLowerCase()) >= 0) break;

    // otherwise, inform user of error and continue asking
    confirm("Error. You should input rock, paper or scissors!");
}

答案 2 :(得分:0)

试试这个

var funcAskUserChoice=function(){
    var userChoice = prompt("Do you choose rock, paper or scissors?");

    // click prompt cancel
    if(userChoice === null){
        return;
    }

    // input is correct
    if(userChoice === "rock" || userChoice === "paper" || userChoice === "scissors"){
        return;
    }

    // click confirm cancel
    if(confirm("Error. You should input rock, paper or scissors!") === false){
        return;
    }

    // ask again
    funcAskUserChoice();
}

// start loop
funcAskUserChoice();

** DEMO **

答案 3 :(得分:0)

我很惊讶编译器没有检测到变量名Again的{​​{1}}部分,并且发现你想让它做一个循环。

无论如何,递归通常是循环的好方法!

inputAgain

在ES6中有尾递归,所以这样做就是&#34; free&#34;。