javascript:if语句比较字符串值不起作用

时间:2016-08-18 03:10:32

标签: javascript arrays string if-statement compare

我在javascript中全新,并想知道为什么我的线路不在这里工作,这是情况:

我写了一个非常简单的猜谜游戏,用户必须从一个单词列表中猜出随机生成的单词。

我想知道为什么代码没有比较用户的输入以查看是否来自列表?

提前谢谢你:)

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;
      }
}

2 个答案:

答案 0 :(得分:2)

我看到你失去了'}'在函数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)

答案 1 :(得分:0)

我看到的问题是你在这里将字符串值与数组guess_input_text!=colors进行比较。这将始终评估为true,因为用户输入的字符串将不会等于颜色数组。这意味着,只要用户输入的颜色与随机颜色不匹配,他们就会得到&#34;请在下面列出的颜色中选择颜色&#34;即使他们选择了阵列中的颜色。

您需要做的是检查用户输入的字符串是否存在于数组中。你可以做的一种方法是改变

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,则还有其他方法可以执行此操作。

您的最后一个条件或多或少是不必要的,因为您已经知道颜色不等于随机颜色并且它在数组中。所以它可以省略,你可以随时发出最后的警报命令。