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


当前回答

我用过的一个技巧是

>>> ("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

其他回答

谢谢你的问题,以及使用数组的解决方案。indexOf方法。

我使用这个解决方案的代码创建了一个inList()函数,在我看来,这将使写作更简单,阅读更清晰:

function inList(psString, psList) 
{
    var laList = psList.split(',');

    var i = laList.length;
    while (i--) {
        if (laList[i] === psString) return true;
    }
    return false;
}

用法:

if (inList('Houston', 'LA,New York,Houston') {
  // THEN do something when your string is in the list
}

我的解决方案的结果是这样的语法:

// Checking to see if var 'column' is in array ['a', 'b', 'c']

if (column.isAmong(['a', 'b', 'c']) {
  // Do something
}

我通过扩展基本的Object原型来实现这一点,像这样:

Object.prototype.isAmong = function (MyArray){
   for (var a=0; a<MyArray.length; a++) {
      if (this === MyArray[a]) { 
          return true;
      }
   }
   return false;
}

我们也可以将该方法命名为isInArray(但可能不是inArray)或简单地命名为isIn。

优点:简单、直接、自文档化。

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

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

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


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

我的小小贡献:

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

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

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

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

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

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