【问题标题】:Compare variable against element of an array (java script)将变量与数组元素进行比较(javascript)
【发布时间】:2017-01-12 05:43:35
【问题描述】:

我正在尝试将数组的每个元素与用户输入进行比较,以在用户的​​输入与数组的任何元素都不匹配时生成一条消息。我用来做的代码如下。

var guess_input;
var finished = false;
var colors = ["Aqua", "BurlyWood", "Cornsilk", "DarkGrey", "DarkRed", "Indigo", "LightGrey"];

while (!finished) {
          guess_input = prompt("I'm thinking of one of these colors:\n\n" + "Aqua, BurlyWood, Cornsilk, DarkGrey, DarkRed, Indigo, LightGrey" + "\n\nWhat is the color I'm thinking of?");
          finished = check_guess();
          }
      }
      function check_guess() {

       if (guess_input !=  colors[0] || guess_input != colors[1] || guess_input != colors[2] || guess_input != colors[3])  {
          alert("Sorry, I don't recognize that color!\n\n" + "Please try again.");
          return false;
        }
}

这段代码的问题是,如果我只从数组中选择一个元素,它就可以正常工作。但是当我使用“或”运算符时,它不起作用。有没有更好的方法来做到这一点?我是 java 脚本新手。

谢谢!

【问题讨论】:

  • 为什么要在循环中声明函数?在外面声明它,这样你就不会每次都迭代函数创建
  • 使用 array.prototype.find() 会更有效
  • @Jonasw,这只有在检查所有元素时才有效,但不仅仅是其中的一部分,如元素 0 ... 2。

标签: javascript arrays


【解决方案1】:

您可以使用logical AND 运算符&&,因为您需要检查所有要检查的颜色。

if (guess_input != colors[0] && guess_input != colors[1] && guess_input != colors[2] && guess_input != colors[3])  {
     alert("Sorry, I don't recognize that color!\n\n" + "Please try again.");
    return false;
}

对于工作代码,您还需要返回 true 以获取找到的颜色。

var guess_input;
var finished = false;
var colors = ["Aqua", "BurlyWood", "Cornsilk", "DarkGrey", "DarkRed", "Indigo", "LightGrey"];

while (!finished) {
    guess_input = prompt("I'm thinking of one of these colors:\n\n" + "Aqua, BurlyWood, Cornsilk, DarkGrey, DarkRed, Indigo, LightGrey" + "\n\nWhat is the color I'm thinking of?");
    finished = check_guess();
}

function check_guess() {
    if (guess_input != colors[0] && guess_input != colors[1] && guess_input != colors[2] && guess_input != colors[3]) {
        alert("Sorry, I don't recognize that color!\n\n" + "Please try again.");
        return false;
    }
    return true; // necessary, otherwise the function returns undefined, which is a falsy value
}

【讨论】:

    【解决方案2】:

    您需要将 guess_inputcolours 数组中的项目进行比较。这是Array.prototype.some() 方法的完美工作,它根据callback 中定义的条件返回truefalse。比如……

    var test_guess = colours.some(function(color) {
        /* 'color' = each item in 'colours' */
        return color === guess_input;
    });
    
    if (test_guess) {
       /* correct .....  */
    } else {
       /* incorrect .... */
    }
    

    这里.some() 开始遍历colours 数组中的所有项,直到条件返回true。如果猜测匹配颜色,变量test_guess 将为true,否则为false

    见:Array.prototype.some() @ MDN

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-10-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多