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

这是我知道的唯一方法:

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

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

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


当前回答

如果您只是试图检查某个值是否包含在集合中,则使用Set更合适,因为数组可以具有重复的值,而Set不能。此外,用set.has替换array.includes可以将性能从O(n2)提高到O(n)。当您必须查找同一集合的多个值时,这将非常有用。因此,如果您只是要查找一个值,那么使用set.has没有任何好处,您可以只使用array.includes。

创建了一个jsbench演示,您可以运行它来检查性能。

测试执行截图:

其他回答

function contains(a, obj) {
    return a.some(function(element){return element == obj;})
}

Array.prototype.some()在第5版中被添加到ECMA-262标准中

适用于所有现代浏览器的解决方案:

function contains(arr, obj) {
  const stringifiedObj = JSON.stringify(obj); // Cache our object to not call `JSON.stringify` on every iteration
  return arr.some(item => JSON.stringify(item) === stringifiedObj);
}

用法:

contains([{a: 1}, {a: 2}], {a: 1}); // true

IE6+解决方案:

function contains(arr, obj) {
  var stringifiedObj = JSON.stringify(obj)
  return arr.some(function (item) {
    return JSON.stringify(item) === stringifiedObj;
  });
}

// .some polyfill, not needed for IE9+
if (!('some' in Array.prototype)) {
  Array.prototype.some = function (tester, that /*opt*/) {
    for (var i = 0, n = this.length; i < n; i++) {
      if (i in this && tester.call(that, this[i], i, this)) return true;
    } return false;
  };
}

用法:

contains([{a: 1}, {a: 2}], {a: 1}); // true

为什么使用JSON.stringify?

Array.indexOf和Array.includes(以及这里的大多数答案)只通过引用而不是通过值进行比较。

[{a: 1}, {a: 2}].includes({a: 1});
// false, because {a: 1} is a new object

奖金

未经优化的ES6单缸套:

[{a: 1}, {a: 2}].some(item => JSON.stringify(item) === JSON.stringify({a: 1));
// true

注:如果键的顺序相同,则按值比较对象的效果会更好,因此为了安全起见,您可以首先使用以下包对键进行排序:https://www.npmjs.com/package/sort-keys


使用性能优化更新了contains函数。谢谢你指出这一点。

如果您只是试图检查某个值是否包含在集合中,则使用Set更合适,因为数组可以具有重复的值,而Set不能。此外,用set.has替换array.includes可以将性能从O(n2)提高到O(n)。当您必须查找同一集合的多个值时,这将非常有用。因此,如果您只是要查找一个值,那么使用set.has没有任何好处,您可以只使用array.includes。

创建了一个jsbench演示,您可以运行它来检查性能。

测试执行截图:

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对象可能不是明智的做法,但有时也可以(如果您意识到这一点和权衡)。

使用Array.indexOf(对象)。对于ECMA7,可以使用Array.includes(对象)。使用ECMA 6,可以使用Array.find(FunctionName),其中FunctionName是用户定义函数以搜索数组中的对象。希望这有帮助!