如何检查如果阵列包括在JavaScript中的对象? [英] How do I check if an array includes an object in JavaScript?

查看:183
本文介绍了如何检查如果阵列包括在JavaScript中的对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么是找出是否一个JavaScript数组包含一个obj中的最简洁,最有效的方式?

What is the most concise and efficient way to find out if a JavaScript array contains an obj?

这是我知道这样做的唯一方法:

This is the only way I know to do it:

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

有没有更好的,更简洁的方式来做到这一点?

Is there a better and more concise way to accomplish this?

这是非常密切相关的堆栈溢出问题的最好的方式找到在JavaScript数组中的项? 的它解决使用中发现一个数组对象的indexOf

This is very closely related to Stack Overflow question Best way to find an item in a JavaScript Array? which addresses finding objects in an array using indexOf.

推荐答案

现代的浏览器<一个href=\"https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/indexOf\"><$c$c>Array#indexOf,能做到这一点。即使是较新的浏览器有<一个href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes#Browser_compatibility\"><$c$c>Array#includes,这确实的究竟的那个,但不幸的是它没有得到广泛的支持。旧的浏览器可以使用支持<一个href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes#Polyfill\">this填充工具。

Modern browsers have Array#indexOf, which can do that. Even newer browsers have Array#includes, which does exactly that, but unfortunately it's not widely supported. Older browsers can be supported using this polyfill.

jQuery提供 $。inArray ,它在功能相当于阵列#的indexOf

jQuery offers $.inArray, which is functionally equivalent to Array#indexOf.

underscore.js ,一个JavaScript工具库,提供 _。包含(列表值) ,别名 _。包括(列表值),无论是其中使用如果传递了一个JavaScript数组的indexOf内部的。

underscore.js, a JavaScript utility library, offers _.contains(list, value), alias _.include(list, value), both of which use indexOf internally if passed a JavaScript array.

其他一些框架提供了类似的方法:

Some other frameworks offer similar methods:

  • Dojo Toolkit: dojo.indexOf(array, value, [fromIndex, findLast])
  • Prototype: array.indexOf(value)
  • MooTools: array.indexOf(value)
  • MochiKit: findValue(array, value)
  • MS Ajax: array.indexOf(value)
  • Ext: Ext.Array.indexOf(array, value, [from])
  • Lodash: _.includes(array, value, [from]) (is _.contains prior 4.0.0)

注意一些框架实现这个作为一个功能,而其他功能添加到阵列的原型。

Notice that some frameworks implement this as a function, while others add the function to the array prototype.

在<一个href=\"http://coffeescript.org/#try:a%20%3D%20[1%2C%202%2C%203%2C%204]%0Aalert%282%20in%20a%29\">CoffeeScript,在操作符是相当于包含

a = [1, 2, 3, 4]
alert(2 in a)

飞镖

var mylist = [1, 2, 3];
assert(mylist.contains(1));
assert(mylist.indexOf(1) == 0);

这篇关于如何检查如果阵列包括在JavaScript中的对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆