虽然循环嵌套if语句不会循环javascript

时间:2015-09-23 17:04:44

标签: javascript while-loop

我不明白为什么,但我的循环不会完成。我应该使用javascript制作一个猜谜游戏,但循环不会实际循环。它只需要一个答案,显示适当的窗口并停止。无论答案如何。这是代码:

<!DOCTYPE >
<html>
<head>
<title>Welcome To The JS Guessing Game</title>
</head>
<script> 

//Initialize the variables that will be needed.
var target;
var target_index;
var guess_input;
var guesses=0;
var finished=false;
var guesses=0;
var colors = ["blue", "cyan", "gold", "green", "magenta", "orange", "red", "white", "yellow"];

function do_game() {
    var random_number = (Math.random()*colors.length);
    var random_number=Math.floor(random_number);
    target=colors[random_number];
    alert(target);
    while (!finished){
        guess_input=prompt("I am thinking of a color in the list below. Can you guess which color?"+"\n\n"+ colors.join() );
        guesses++;
        if (guess_input!=target){
            alert("no")
            return true;
        }
        alert("yes!!")
        return false;
    }
}
</script>
<body onload="do_game()">
</body>
</html>

现在我真的不明白我做错了什么,并且控制台在任何浏览器中都没有出错:/ 我真的很感激帮助!

干杯,

大卫

3 个答案:

答案 0 :(得分:0)

问题是当输入错误答案并运行代码时,您正在退出while循环:

if (guess_input!=target){
    alert("no")
    return true;
}

请考虑使用continue语句,而不是返回值。

if (guess_input!=target){
    alert("no")
    continue;
}

这将跳转到循环的下一次迭代,保持在循环内但不执行alert("yes!!")。这是一个JSFiddle来演示。希望这可以帮助!如果您有任何问题,请告诉我。

(根据您对问题的评论,您并不真正需要finished变量,只需使用while(true)就足够了。)

答案 1 :(得分:0)

finished设置为true(无需将其设置为false,因为在您更改之前它始终为false。如果您需要在循环之后返回finished(我不认为您这样做),我已在声明中添加了相应的内容。您还需要在其中添加else子句,或者即使符合条件,finished也会在代码中设置为true

function do_game() {
    var random_number = (Math.random()*colors.length);
    var random_number=Math.floor(random_number);
    target=colors[random_number];
    while (!finished){
        guess_input=prompt("I am thinking of a color in the list below. Can you guess which color?"+"\n\n"+ colors.join() );
        guesses++;
        if (guess_input!=target){
            alert("no");
        } else {
          alert("yes!!");
          finished = true;
        }
    }
    return finished;
}

答案 2 :(得分:0)

无论条件如何,您都返回一个布尔值。看看这里的代码:https://jsfiddle.net/zmdcL4h4/1/

//Initialize the variables that will be needed.
var target;
var target_index;
var guess_input;
var guesses=0;
var finished=false;
var guesses=0;
var colors = ["blue", "cyan", "gold", "green", "magenta", "orange", "red", "white", "yellow"];

function do_game() {
    var random_number = (Math.random()*colors.length);
    var random_number=Math.floor(random_number);
    target=colors[random_number];
    alert(target);
    while (!finished){
        guess_input=prompt("I am thinking of a color in the list below. Can you guess which color?"+"\n\n"+ colors.join() );
        if(!guess_input){
            finished = true;
            return true;
        }
        guesses++;
        if (guess_input!=target){
            alert("no")
        }
        else
            return true;
    }
}