找出JavaScript数组是否包含值的最简洁有效的方法是什么?

这是我知道的唯一方法:

function contains(a, obj) {
    for (var i = 0; i < a.length; i++) {
        if (a[i] === obj) {
            return true;
        }
    }
    return false;
}

有没有更好、更简洁的方法来实现这一点?

这与堆栈溢出问题密切相关。在JavaScript数组中查找项目的最佳方法是什么?它解决了使用indexOf查找数组中的对象的问题。


当前回答

ECMAScript 7引入了Array.prototype.includes。

它可以这样使用:

[1, 2, 3].includes(2); // true
[1, 2, 3].includes(4); // false

它还接受来自Index的可选第二个参数:

[1, 2, 3].includes(3, 3); // false
[1, 2, 3].includes(3, -1); // true

与使用严格相等比较的indexOf不同,indexOf包括使用SameValueZero相等算法的比较。这意味着您可以检测阵列是否包含NaN:

[1, 2, NaN].includes(NaN); // true

与indexOf不同,includes不会跳过缺少的索引:

new Array(5).includes(undefined); // true

它可以是多填充的,以使其在所有浏览器上都可以使用。

其他回答

字面意思:

(使用Firefox v3.6,如前所述,带有for in注意事项(然而,下面的用法可能支持中的这一目的!即,枚举通过属性索引实际存在的数组元素(尤其是,数组长度属性未在for in属性列表中枚举!)。)

(拖放以下完整URI以进行即时模式浏览器测试。)

JavaScript:

  function ObjInRA(ra){var has=false; for(i in ra){has=true; break;} return has;}

  function check(ra){
      return ['There is ',ObjInRA(ra)?'an':'NO',' object in [',ra,'].'].join('')
  }
  alert([
            check([{}]), check([]), check([,2,3]),
            check(['']), '\t (a null string)', check([,,,])
        ].join('\n'));

其显示:

There is an object in [[object Object]].
There is NO object in [].
There is an object in [,2,3].
There is an object in [].
     (a null string)
There is NO object in [,,].

皱纹:如果要查找“特定”对象,请考虑:

JavaScript:警报({}!={});警报({}!=={});

因此:

JavaScript:

 obj = {prop:"value"}; 
 ra1 = [obj]; 
 ra2 = [{prop:"value"}];
 alert(ra1[0] == obj); 
 alert(ra2[0] == obj);

ra2通常被认为“包含”obj作为文本实体{prop:“value”}。

一个非常粗糙、简单、幼稚的解决方案(如代码需要增强资格):

JavaScript:

  obj={prop:"value"};   ra2=[{prop:"value"}];
  alert(
    ra2 . toSource() . indexOf( obj.toSource().match(/^.(.*).$/)[1] ) != -1 ?
      'found' :
      'missing' );

请参阅ref:在JavaScript数组中搜索对象。

类似的事情:通过“search lambda”查找第一个元素:

Array.prototype.find = function(search_lambda) {
  return this[this.map(search_lambda).indexOf(true)];
};

用法:

[1,3,4,5,8,3,5].find(function(item) { return item % 2 == 0 })
=> 4

咖啡脚本也一样:

Array.prototype.find = (search_lambda) -> @[@map(search_lambda).indexOf(true)]

indexOf可能是,但它是“ECMA-262标准的JavaScript扩展;因此,它可能不会出现在标准的其他实现中。”

例子:

[1, 2, 3].indexOf(1) => 0
["foo", "bar", "baz"].indexOf("bar") => 1
[1, 2, 3].indexOf(4) => -1

AFAICS Microsoft没有提供某种替代方案,但如果您愿意,可以在Internet Explorer(以及其他不支持indexOf的浏览器)中的数组中添加类似的功能,正如Google快速搜索所显示的(例如,这一个)。

使用RegExp:

console.log(new RegExp('26242').test(['23525', '26242', '25272'].join(''))) // true

Use:

Array.prototype.contains = function(x){
  var retVal = -1;

  // x is a primitive type
  if(["string","number"].indexOf(typeof x)>=0 ){ retVal = this.indexOf(x);}

  // x is a function
  else if(typeof x =="function") for(var ix in this){
    if((this[ix]+"")==(x+"")) retVal = ix;
  }

  //x is an object...
  else {
    var sx=JSON.stringify(x);
    for(var ix in this){
      if(typeof this[ix] =="object" && JSON.stringify(this[ix])==sx) retVal = ix;
    }
  }

  //Return False if -1 else number if numeric otherwise string
  return (retVal === -1)?false : ( isNaN(+retVal) ? retVal : +retVal);
}

我知道这不是最好的方法,但由于没有本机的IComparable方法来在对象之间进行交互,我想这是比较数组中两个实体所能做到的。此外,扩展Array对象可能不是明智的做法,但有时也可以(如果您意识到这一点和权衡)。