[英]Javascript: What is wrong with this code?
<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>
When I try to run even if I enter correct color it shows that "Sorry, I don't recognize your color", when I tried to check what value it is taking in guess it is showing -1. 即使我输入正确的颜色,当我尝试运行时,它也会显示“对不起,我无法识别您的颜色”,而当我尝试检查其值时,猜测它显示为-1。 Please help! 请帮忙!
var colors = ["blue ", "coral ", "orchid ", "red ", "cyan ", "dark orange", "aqua ","yellow ", "gold ", "brown "];4
Each word has a space after it. 每个词后面都有一个空格。 Remove the space and it will work. 删除空间,它将起作用。 Also whats with the 4? 还有什么4? You can remove that too. 您也可以删除它。
You have a trailing space inside of the double quotes behind each color name. 每个颜色名称后面的双引号内都有一个尾随空格。 If you remove the spaces you should be good to go. 如果您删除空格,那应该很好。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.