Javascript:这段代码有什么问题?

时间:2016-09-26 13:43:36

标签: javascript

  <html>
   <head>
    <script>
 var play;
 var target;
 var count = 0;
 var guess;
 var colors = ["blue ", "coral ", "orchid ", "red ", "cyan ", "dark orange", "aqua ", "yellow ", "gold ", "brown "];

 var colors = colors.sort();

 function do_this() {
   var choose = Math.floor(Math.random() * (colors.length));
   target = colors[choose];
   alert("The correct answer is " + target);
   alert(typeof(colors));
   while (true) {
     play = prompt("I am thinking one of these colors\n\n" + colors + "What color am I thinking of?");
     guess = colors.indexOf(play);

     count = count + 1;
     if (guess == -1) {
       alert("Sorry, I don't recognize your color");
       continue;
     }
     if (guess > target) {
       alert("Sorry, your guess is not correct\n\n" + "Hint: your color is alphabetically higher than mine\n\n Please try again");
       continue;
     }
     if (guess < target) {
       alert("Sorry, your guess is not correct\n\n" + "Hint: your color is alphabetically lower than mine\n\n Please try again");
       continue;
     }
     alert("Congratulations! You have guessed the color\n\n!" + "It took you" + count + "guesses to finish the game\n\n" +
       "You can see the color of the background");
     return true;
   }
 }

    </script>
    <body onload = "do_this()">
    </body>
    </head>
    </html>

当我尝试跑步时,即使我输入正确的颜色,也会显示&#34;对不起,我不认识你的颜色&#34;,当我试图检查它的价值时猜测它是显示-1。请帮忙!

2 个答案:

答案 0 :(得分:1)

var colors = ["blue ", "coral ", "orchid ", "red ", "cyan ", "dark orange", "aqua ","yellow ", "gold ", "brown "];4

每个单词后面都有一个空格。删除空间,它将工作。 4还有什么?你也可以删除它。

答案 1 :(得分:0)

每个颜色名称后面的双引号内都有一个尾随空格。如果你删除空格,你应该去。