即使条件满足,循环也不会停止

时间:2015-12-09 06:37:05

标签: javascript arrays while-loop

功能性:

用户是根据猜谜游戏输入颜色。当答案错误时,提示将保持提示,提示只会在用户设置正确答案时退出。

我做了什么: 已经使用while循环来检查条件。在while循环中,只有当它等于target时才设置while循环,而target是系统随机选择的颜色

问题: 提示最初将颜色设置为答案,但即使用户设置了正确的答案,也会提示循环。

如果设置了其中一种颜色,如何退出循环?

<html>

<head>
  <title>Color Guessing Game</title>
</head>

<body onload="do_game()">
  <script>
    function do_game() {
        var color = ["blue", "cyan", "gray", "green", "magenta", "orange", "red", "white", "yellow"];
        var guess_input_text, guess_input, finished = false,
          target, guesses = 0;

        var target_index = color[0, 8];
        target = target_index;
        alert(target);
        while (!finished) {
          guess_input_text = prompt("I am thinking of these colors:" +
            "\n\n blue, cyan, gray, green, magenta, orange, red, white, yellow" + "\n\n what color am I thinking of?");
          guess_input = parseInt(guess_input_text);
          guesses += 1;
          finished = target;
        }
      }
  </script>
</body>

</html>

3 个答案:

答案 0 :(得分:2)

如果输入与目标相同,请尝试使用此代码控制循环的每一轮,如果它们相同则完成后才会生效:

function do_game() {
    var color = ["blue", "cyan", "gray", "green", "magenta", "orange", "red", "white", "yellow"];
    var guess_input_text, guess_input, finished = false,
      target, guesses = 0;

    var rnd = Math.floor((Math.random() * 9) + 0); //Makes a random number between 0 and 8
    target = color[rnd]; //sets the target to a random color from the color array
    while (!finished) {
      guess_input_text = prompt("I am thinking of these colors:" +
        "\n\n blue, cyan, gray, green, magenta, orange, red, white, yellow" + "\n\n what color am I thinking of?"); //gets alert-input from user
      guesses += 1;
      if(guess_input_text == target){//checks if input from user and target are the same
        finished = true;
      }
    }
  }

答案 1 :(得分:1)

另一种没有完成变量的方法。使用break

var target_text = color[0, 8];
...
while (true) {
      guess_input_text = prompt("I am thinking of these colors:" +
        "\n\n blue, cyan, gray, green, magenta, orange, red, white, yellow" + "\n\n what color am I thinking of?");

      guesses += 1;
      if(guess_input_text == target_text){
       //guessed correct answer
       break;
      }
}

答案 2 :(得分:1)

您的代码没有按照您的想法执行。

这不会得到随机值的索引,它会得到最后一个值。

var target_index = color[0,8];

这将得到一个随机数组值:     var rand = color [Math.floor(Math.random()* color.length)];

获得胜利价值后,进行指数比较毫无意义。您可以简单地比较字符串,因为prompt()返回输入响应的字符串(为简洁起见,修改了提示文本)。

var finished = false;
while (!finished)
{
    var input = prompt("What color am I thinking of?");
    finished = (input.toLowerCase() === rand);
}