找出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

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

其他回答

我建议使用下划线库,因为它返回值,并且支持所有浏览器。

下芯js

 var findValue = _.find(array, function(item) {
    return item.id == obj.id;
 });

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

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

上面的答案假设是基元类型,但如果您想知道数组是否包含具有某种特征的对象,array.protocol.some()是一个很好的解决方案:

const items = [ {a: '1'}, {a: '2'}, {a: '3'} ]

items.some(item => item.a === '3')  // returns true
items.some(item => item.a === '4')  // returns false

它的好处是,一旦找到元素,迭代就被中止,从而避免了不必要的迭代周期。

此外,它很适合if语句,因为它返回布尔值:

if (items.some(item => item.a === '3')) {
  // do something
}

*正如jamess在评论中指出的那样,在2018年9月回答这个问题时,Array.protocol.some()是完全支持的:caniuse.com支持表

有几种方法可以找到答案。您可以使用内置的Array方法。最常用的是数组查找方法。

const arr1 = [1, 2, 3, 4, 5]
const result = arr1.find(ele => ele === 4)
console.log(result) //4

const result2 = arr1.find(ele => ele === 6)
console.log(result2) //undefined
/* 
If the element is present inside the array
then it will return the first element that
satisfies the given condition. Otherwise
undefined will return.
*/

使用indexOf()

可以使用indexOf()方法检查数组中是否存在给定的值或元素。如果找到数组中元素的索引,indexOf()方法返回该元素的索引;如果找不到,则返回-1。让我们看一下以下示例:

var fruits=[“苹果”、“香蕉”、“芒果”、“橙子”、“木瓜”];var a=“芒果”;checkArray(a,水果);函数checkArray(a,fruits){//检查fruits数组中是否存在值如果(fruits.indexOf(a)!==-1) {return document.write(“true”);}其他{return document.write(“false”);}}

使用include()方法

ES6引入了includes()方法来非常容易地执行此任务。但是,此方法只返回true或false,而不返回索引号:

var fruits=[“苹果”、“香蕉”、“芒果”、“橙子”、“木瓜”];警报(水果,包括(“香蕉”));//输出:真警报(水果,包括(“椰子”));//输出:假警报(水果,包括(“橙色”));//输出:真警报(水果,包括(“樱桃”));//输出:假

如需进一步参考,请在此处结账