2016-09-26 139 views
0
<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> 

當我嘗試運行時,即使輸入了正確的顏色,它也會顯示「對不起,我不認出你的顏色」,當我嘗試檢查它在猜測中顯示的值是-1時。請幫忙!Javascript:這段代碼有什麼問題?

+0

它確實工作,當您在提示中的顏色名稱之後輸入空格時 –

回答

1

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

每個字詞都加上一個空格。刪除空間,它會工作。還有什麼與4?你也可以刪除它。

0

在每個顏色名稱後面的雙引號內有一個尾隨空格。如果你刪除空間,你應該很好去。