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

这是我知道的唯一方法:

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

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

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


当前回答

原型是这样做的:

/**
 *  Array#indexOf(item[, offset = 0]) -> Number
 *  - item (?): A value that may or may not be in the array.
 *  - offset (Number): The number of initial items to skip before beginning the
 *      search.
 *
 *  Returns the position of the first occurrence of `item` within the array &mdash; or
 *  `-1` if `item` doesn't exist in the array.
**/
function indexOf(item, i) {
  i || (i = 0);
  var length = this.length;
  if (i < 0) i = length + i;
  for (; i < length; i++)
    if (this[i] === item) return i;
  return -1;
}

另请参见此处了解它们是如何连接的。

其他回答

想一想,如果您多次调用此调用,那么使用关联数组Map使用哈希函数进行查找会更有效。

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map

使用idnexOf()是一个很好的解决方案,但您应该隐藏嵌入的实现indexOf(()函数,该函数使用~运算符返回-1:

function include(arr,obj) { 
    return !!(~arr.indexOf(obj)); 
} 

扩展JavaScript数组对象是一个非常糟糕的主意,因为您在for-in循环中引入了新的财产(自定义方法),这可能会破坏现有的脚本。几年前,Prototype库的作者不得不重新设计他们的库实现,以消除这种情况。

如果您不需要担心与页面上运行的其他JavaScript的兼容性,那就去尝试吧,否则,我会推荐更尴尬但更安全的独立函数解决方案。

它有一个参数:对象的数组数。数组中的每个对象都有两个由x和y表示的整数财产。该函数必须返回数组中满足numbers.x==numbers.y的所有此类对象的计数

var数=〔{x:1,y:1},{x:2,y:3},{x:3,y:3},{x:3,y:4},{x:4,y:5}];变量计数=0;var n=数字长度;对于(变量i=0;i<n;i++){如果(数字[i].x==数字[i].y){count+=1;}}警报(计数);

可以使用findIndex函数检查数组是否具有特定值。

arrObj.findIndex(obj => obj === comparedValue) !== -1;

如果arrObj包含comparedValue,则返回true,否则返回false。