找出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(x)=-1是实现这一点的最简洁的方法(并且已经被非Internet Explorer浏览器支持了十多年……),它不是O(1),而是O(N),这很可怕。如果您的数组不会改变,您可以将数组转换为哈希表,然后执行表[x]==未定义或==未定义:

Array.prototype.toTable = function() {
    var t = {};
    this.forEach(function(x){t[x]=true});
    return t;
}

演示:

var toRemove = [2,4].toTable();
[1,2,3,4,5].filter(function(x){return toRemove[x]===undefined})

(不幸的是,虽然您可以创建Array.prototype.contains来“冻结”数组并将哈希表存储在this._cache中,但如果您选择稍后编辑数组,则会产生错误的结果。与Python不同,JavaScript没有足够的钩子来保持这种状态。)

其他回答

如果你使用的是JavaScript 1.6或更高版本(Firefox 1.5或更高),你可以使用Array.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

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

只是另一种选择

// usage: if ( ['a','b','c','d'].contains('b') ) { ... }
Array.prototype.contains = function(value){
    for (var key in this)
        if (this[key] === value) return true;
    return false;
}

要小心,因为用自定义方法重载javascript数组对象会破坏其他java脚本的行为,从而导致意外行为。

或此解决方案:

Array.prototype.includes = function (object) {
  return !!+~this.indexOf(object);
};

假设您定义了这样一个数组:

const array = [1, 2, 3, 4]

下面是三种检查其中是否有3的方法。所有这些都返回true或false。

本机阵列方法(自ES2016以来)(兼容性表)

array.includes(3) // true

作为自定义数组方法(ES2016之前)

// Prefixing the method with '_' to avoid name clashes
Object.defineProperty(Array.prototype, '_includes', { value: function (v) { return this.indexOf(v) !== -1 }})
array._includes(3) // true

简单的功能

const includes = (a, v) => a.indexOf(v) !== -1
includes(array, 3) // true