在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如果没有一些语法糖就不能正常工作。


当前回答

RegExp是通用的,但我知道您使用的是数组。所以,看看这个方法。我过去经常用它,它非常有效,而且非常快!

var str = 'some string with a';
var list = ['a', 'b', 'c'];
var rx = new RegExp(list.join('|'));

rx.test(str);

您还可以应用一些修改,即:

一行程序

new RegExp(list.join('|')).test(str);

不分大小写

var rx = new RegExp(list.join('|').concat('/i'));

还有很多其他的!

其他回答

我的小小贡献:

function fnListIndexOf(pList, pValue)
{
    return pList.split(",").indexOf (pValue);
}

fnListIndexOf("1,2,3,4,5,a,b,c","a")

我用过的一个技巧是

>>> ("something" in {"a string":"", "somthing":"", "another string":""})
false
>>> ("something" in {"a string":"", "something":"", "another string":""})
true

你可以这样做

>>> a = ["a string", "something", "another string"];
>>> b = {};
>>> for(var i=0; i<a.length;i++){b[a[i]]="";} /* Transform the array in a dict */
>>> ("something" in b)
true

SLaks回答的简化版本也适用:

if ('abcdefghij'.indexOf(str) >= 0) {
    // Do something
}

....因为字符串本身就是数组。:)

如果需要,可以像我前面描述的那样为Internet Explorer实现indexof函数。

看起来你需要使用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的变量应该告诉你它们包含什么(名词)。

这是我的:

String.prototype.inList=function(list){
    return (Array.apply(null, arguments).indexOf(this.toString()) != -1)
}

var x = 'abc';
if (x.inList('aaa','bbb','abc'))
    console.log('yes');
else
    console.log('no');

如果你可以传递一个数组,这个会更快:

String.prototype.inList=function(list){
    return (list.indexOf(this.toString()) != -1)
}

var x = 'abc';
if (x.inList(['aaa','bbb','abc']))
    console.log('yes')

下面是jsperf: http://jsperf.com/bmcgin-inlsit