Javascript - 我找不到错误的位置。

时间:2016-03-26 11:25:13

标签: javascript

我完全不知道为什么这段代码没有运行。它应该是一个颜色猜谜游戏。它运行一次,然后它只显示空白屏幕。

应该从一个或多个颜色随机选择一种颜色然后它要求用户输入并将其与所选颜色进行比较并相应地输出。

<!doctype html>
<html>
<head>
    <title>JavaScript Guessing Game</title>
    <script>
        var target;            
        var guess_input_text;   
        var guess_input;      
        var finished = false;   
        var guesses = 0;
        var colors = ["blue","cyan","gold","grey","green","magenta", "orange", "red","white","yellow"];
        var scolors = colors.sort();

        function do_game() {
            var random_number = Math.random() * 10;
            var random_number_integer = Math.floor(random_number);
            target_index = random_number_integer;
            target = colors[target_index];

            while (!finished) {
                guess_input = (prompt("I am thinking of one of these colors " + colors.join(", ") + ".\n\n What color am I thinking of?")).toLowerCase();
                guesses += 1;   
                finished = check_guess();
            }
        }

        function check_guess() {
            if (!(colors.indexOf(guess_input) >= 0)) {
                alert("Sorry I don't recognize your color\n\n" +
                      "Please try again.");
                return false;
            }
            if (scolors.indexOf(guess_input) > (scolors.indexOf(target))) {
                alert("Sorry, your guess is not correct\n\n" + "Hint: Your color is alphabetically higher than mine\n\n"+"Please try again.");
                return false;
            }
            if (scolors.indexOf(guess_input) < (scolors.indexOf(target))) {
                alert("Sorry, your guess is not correct\n\n" + "Hint: Your color is alphabetically lower than mine\n\n"+"Please try again.");
                return false;
            }
            else{
            alert("Congratulations! You've guessed the color!+ 
                  ".\n\nIt took you " + guesses + 
                  " to finish the game!\n\n You can see the color in the background");
            return true;   
        }
        }
    </script>
   
</head>
<body onload="do_game()">

</body>
</html>

2 个答案:

答案 0 :(得分:3)

你缺少双引号:

alert("Congratulations! You've guessed the color!"+ 
//-----------------------------------------------^

我建议您在浏览器中打开控制台(在chrome ctrl + shift + i中),运行代码并在下次查找错误。

答案 1 :(得分:-1)

如果您使用JavaScript IDE,例如原子,webstorm和崇高。你可以很容易地找到错误。

enter image description here