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

这是我知道的唯一方法:

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

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

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


当前回答

使用lodash的一些功能。

它简洁、准确,并且具有强大的跨平台支持。

接受的答案甚至不符合要求。

要求:推荐最简洁有效的方法来确定JavaScript数组是否包含对象。

接受答案:

$.inArray({'b': 2}, [{'a': 1}, {'b': 2}])
> -1

我的建议:

_.some([{'a': 1}, {'b': 2}], {'b': 2})
> true

笔记:

$.inArray可以很好地确定标量数组中是否存在标量值。。。

$.inArray(2, [1,2])
> 1

…但这个问题显然需要一种有效的方法来确定数组中是否包含对象。

为了处理标量和对象,可以执行以下操作:

(_.isObject(item)) ? _.some(ary, item) : (_.indexOf(ary, item) > -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

Use:

function isInArray(array, search)
{
    return array.indexOf(search) >= 0;
}

// Usage
if(isInArray(my_array, "my_value"))
{
    //...
}

使用Array.prototype.includes,例如:

常量水果=['conot','香蕉','苹果']const doesFruitsHaveCoconut=水果.包括('conot')//trueconsole.log(doesFruitsHaveCoconut)

可以从MDN阅读此文档:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes

使用RegExp:

console.log(new RegExp('26242').test(['23525', '26242', '25272'].join(''))) // true

类似的事情:通过“search lambda”查找第一个元素:

Array.prototype.find = function(search_lambda) {
  return this[this.map(search_lambda).indexOf(true)];
};

用法:

[1,3,4,5,8,3,5].find(function(item) { return item % 2 == 0 })
=> 4

咖啡脚本也一样:

Array.prototype.find = (search_lambda) -> @[@map(search_lambda).indexOf(true)]