javascript - 即使条件满足后,while 循环也不会停止

标签 javascript arrays while-loop

功能:

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

我做了什么: 使用 while 循环来检查条件。 while循环中,设置while循环只有等于target时才结束,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>

最佳答案

尝试这段代码,如果输入与目标相同,则控制每一轮循环,如果它们相同,则完成为 true:

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;
      }
    }
  }

关于javascript - 即使条件满足后,while 循环也不会停止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34172221/

相关文章:

java - 在线程内使用 for 循环与类似的 while 循环行为不匹配

php - 使用 jQuery 发送很长的字符串 PHP

Vue JS 和 Velocity JS 的 Javascript 内存泄漏

javascript - 通过 jQuery 为 html 元素的属性分配空字符串

c - 将未初始化的字符数组传递给函数。崩溃

c++在没有try Catch block 的情况下捕获错误输入

.net 编译器错误 “Not all code paths return a value” 上的任务方法

javascript - 使用嵌套/链接保存解析无响应

将 char 数组复制到另一个 char 数组而不发生内存泄漏

c - fgets 在退出 EOF 之前循环多次