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

这是我知道的唯一方法:

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

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

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


当前回答

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

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

其他回答

原型是这样做的:

/**
 *  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;
}

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

如果您正在重复检查数组中是否存在对象,您可能应该查看

通过在数组中执行插入排序(将新对象放在正确的位置),始终保持数组排序将更新对象设置为删除+排序插入操作和在contains(a,obj)中使用二进制搜索查找。

这绝不是最好的,但我只是在发挥创意,加入到曲目中。

不要使用此

Object.defineProperty(Array.prototype,“exists”{值:函数(元素,索引){var索引=索引||0返回索引==this.length-1:this[index]==元素?索引:this.exists(元素,++索引)}})//输出1console.log(['one','two'].exists('two'));//输出-1console.log(['one','two'].existes('tree'));console.log(['one','two','three','four'].exists('fur'));

这里是Array.indexOf的JavaScript 1.6兼容实现:

if (!Array.indexOf) {
    Array.indexOf = [].indexOf ?
        function(arr, obj, from) {
            return arr.indexOf(obj, from);
        } :
        function(arr, obj, from) { // (for IE6)
            var l = arr.length,
                i = from ? parseInt((1 * from) + (from < 0 ? l : 0), 10) : 0;
            i = i < 0 ? 0 : i;
            for (; i < l; i++) {
                if (i in arr && arr[i] === obj) {
                    return i;
                }
            }
            return -1;
        };
}

有两种方法使这一点很容易实现(包括,一些,find,findIndex)

常量数组=[1,2,3,4,5,6,7];console.log(array.includes(3));//includes()确定数组的条目中是否包含某个值console.log(array.some(x=>x===3));//some()测试数组中是否至少有一个元素通过了所提供函数实现的测试console.log(array.find(x=>x===3)?真:假);//find()返回所提供数组中满足所提供测试函数的第一个元素的值console.log(array.findIndex(x=>x===3)>-1);//findIndex()返回数组中满足所提供测试函数的第一个元素的索引,否则返回-1。

更多关于includes,some,find,findIndex