的javascript:if语句比较不工作
问题描述:
我在javascript全新的字符串值,不知道为什么我没有线在这里工作,这里的情况是:的javascript:if语句比较不工作
我写了一个非常简单的猜谜游戏,其中用户必须从单词列表中猜测随机生成的单词。
我不知道为什么代码是不是比较用户的输入,看是否是从列表或没有?
预先感谢您:)
var target_index;
var guess_input_text;
var finished=false;
var number_of_guesses = 0;
var colors = ["pink", 'olive', 'lime', 'orange', 'yellow', 'purple', 'indigo', 'blue', 'gray', 'black'];
var guesses = 0;
var color;
function do_game() {
var random_number = Math.random()*9;
var random_number_intiger = Math.floor(random_number);
target_index = random_number_intiger;
color = colors[target_index];
alert(color);
while (!finished){
guess_input_text = prompt('I am thinking of one of these colors.\n\n' + colors + '\n\n What do you think it is?');
guesses++;
alert(guess_input_text);
finished = check_guess();
}
}
function check_guess(){
if (guess_input_text===color){ //this works
return true;
}
if (guess_input_text!=color && guess_input_text!=colors){ //why this is not working :(
alert('Please choose your color among the colors listed below:\n\n' + colors);
return false;
}
if (guess_input_text!=color && guess_input_text==colors){ //this is not working too
alert('You are a bit off');
return false;
}
}
答
我看见你在功能do_game()
function do_game() {
var random_number = Math.random()*9;
var random_number_intiger = Math.floor(random_number);
target_index = random_number_intiger;
color = colors[target_index];
alert(color);
while (!finished){
guess_input_text = prompt('I am thinking of one of these colors.\n\n' + colors + '\n\n What do you think it is?');
guesses++;
alert(guess_input_text);
finished = check_guess();
}//Add here
}
变化失去了 '}':
if (guess_input_text!=color && guess_input_text!=colors)
if (guess_input_text!=color && guess_input_text==colors)
到:
if (guess_input_text!=color && colors.indexOf(guess_input_text) < 0)
if (guess_input_text!=color && colors.indexOf(guess_input_text) >= 0)
答
的主要问题,我看到的是,你是一个字符串值,这里guess_input_text!=colors
比较数组。由于用户输入的字符串永远不会等于颜色数组,因此这将始终评估为真。这意味着,只要用户输入的颜色与随机颜色不匹配,即使他们选择了阵列中的颜色,他们也会得到“请在下面列出的颜色中选择您的颜色”。
你需要做的是,如果由用户输入的字符串数组中存在检查。你能做到这一点的方法之一是改变
if (guess_input_text!=color && guess_input_text!=colors){ //why this is not working :(
到
if (guess_input_text!=color && colors.indexOf(guess_input_text)>=0){ //this will work if your browser/platform supports it :)
的indexOf如果不能提供给你,还有其他方法可以做到这一点。
你的最后一个条件是多还是少不必要的,因为你已经知道,颜色不等于随机的颜色,它是在数组中。所以它可以被省略,并且您可以随时发出您的最终警报命令。
你不能用一个数组'colors'比较字符串'guess_input_text'。它永远是不平等的。 – 4castle