在SQL中,我们可以看到一个字符串是否像这样在一个列表中:

Column IN ('a', 'b', 'c')

JavaScript中有什么好方法呢?这样做太笨拙了:

if (expression1 || expression2 || str === 'a' || str === 'b' || str === 'c') {
   // do something
}

我不确定它的表现和清晰度:

if (expression1 || expression2 || {a:1, b:1, c:1}[str]) {
   // do something
}

或者可以使用switch函数:

var str = 'a',
   flag = false;

switch (str) {
   case 'a':
   case 'b':
   case 'c':
      flag = true;
   default:
}

if (expression1 || expression2 || flag) {
   // do something
}

但这是一个可怕的混乱。什么好主意吗?

在这种情况下,我必须使用Internet Explorer 7,因为它是用于公司内部网页面的。所以['a', 'b', 'c']. indexof (str) !== -1如果没有一些语法糖就不能正常工作。


当前回答

你可以调用indexOf:

if (['a', 'b', 'c'].indexOf(str) >= 0) {
    //do something
}

其他回答

除了indexOf(这是其他海报的建议),使用原型的Enumerable.include()可以使这更简洁:

var list = ['a', 'b', 'c'];
if (list.includes(str)) {
  // do stuff
}

使用indexOf(它不支持IE8)。

if (['apple', 'cherry', 'orange', 'banana'].indexOf(value) >= 0) {
    // found
}

为了支持IE8,你可以实现Mozilla的indexOf。

if (!Array.prototype.indexOf) {
    // indexOf polyfill code here
}

通过String.prototype.match (docs)实现正则表达式。

if (fruit.match(/^(banana|lemon|mango|pineapple)$/)) {

}

看起来你需要使用in_array函数。

jQuery -> inArray

Prototype -> Array.indexOf

或者,如果你不使用jQuery或Prototype,看看这些例子:

http://phpjs.org/functions/in_array:432 http://www.bitrepository.com/equivalent-of-phps-in_array-function.html http://codingforums.com/showthread.php?t=63796

风格注意:命名为thisthing, thatthing的变量应该告诉你它们包含什么(名词)。

我很惊讶居然没有人提到一个接受字符串和列表的简单函数。

function in_list(needle, hay)
{
    var i, len;

    for (i = 0, len = hay.length; i < len; i++)
    {
        if (hay[i] == needle) { return true; }
    }

    return false;
}

var alist = ["test"];

console.log(in_list("test", alist));

大多数答案都建议使用Array.prototype.indexOf方法,唯一的问题是它不能在IE9之前的任何IE版本上工作。

作为替代,我给你留下了两个可以在所有浏览器上工作的选项:

if (/Foo|Bar|Baz/.test(str)) {
  // ...
}


if (str.match("Foo|Bar|Baz")) {
  // ...
}