如何检查数组是否在JavaScript中包含值? [英] How do I check if an array includes a value in JavaScript?

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

问题描述

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

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

这是我唯一知道的方法:

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?

这与Stack Overflow问题 在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.

推荐答案

现代浏览器具有 Array#includes ,精确地 ,并且所有人都广泛支持 除了IE:

Modern browsers have Array#includes, which does exactly that and is widely supported by everyone except IE:

console.log(['joe', 'jane', 'mary'].includes('jane')); //true

您也可以使用 Array#indexOf

You can also use Array#indexOf, which is less direct, but doesn't require polyfills for outdated browsers.

许多框架还提供了类似的方法:

Many frameworks also offer similar methods:

  • jQuery: $.inArray(value, array, [fromIndex])
  • Underscore.js: _.contains(array, value) (also aliased as _.include and _.includes)
  • 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.contains(array, value)
  • Lodash: _.includes(array, value, [from]) (is _.contains prior 4.0.0)
  • Ramda: R.includes(value, array)

请注意,某些框架将其实现为函数,而其他框架则将该函数添加到数组原型中。

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

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

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