找出JavaScript数组是否包含值的最简洁有效的方法是什么?
这是我知道的唯一方法:
function contains(a, obj) {
for (var i = 0; i < a.length; i++) {
if (a[i] === obj) {
return true;
}
}
return false;
}
有没有更好、更简洁的方法来实现这一点?
这与堆栈溢出问题密切相关。在JavaScript数组中查找项目的最佳方法是什么?它解决了使用indexOf查找数组中的对象的问题。
现代浏览器具有Array#includes,这正是做到这一点的,除IE外,所有人都广泛支持它:
console.log(['joe','jane','mary']includes('jane]))//真的
您也可以使用Array#indexOf,它不那么直接,但对于过时的浏览器不需要polyfill。
console.log(['joe','jane','smary'].indexOf('jane')>=0)//真的
许多框架也提供类似的方法:
jQuery:$.inArray(value,array,[fromIndex])Undercore.js:_.inclus(数组,值)(别名为_.include和_.includes)DojoToolkit:Dojo.indexOf(array,value,[fromIndex,findLast])原型:array.indexOf(value)MooTools:array.indexOf(value)MochiKit:findValue(数组,值)MS Ajax:array.indexOf(值)Ext:Ext.Array.contains(数组,值)Lodash:_.includes(array,value,[from])(是_.包含4.0.0之前的版本)Ramda:R.includes(值,数组)
请注意,一些框架将其作为函数实现,而另一些框架将该函数添加到数组原型中。
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
它可以是多填充的,以使其在所有浏览器上都可以使用。
假设您定义了这样一个数组:
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
indexOf可能是,但它是“ECMA-262标准的JavaScript扩展;因此,它可能不会出现在标准的其他实现中。”
例子:
[1, 2, 3].indexOf(1) => 0
["foo", "bar", "baz"].indexOf("bar") => 1
[1, 2, 3].indexOf(4) => -1
AFAICS Microsoft没有提供某种替代方案,但如果您愿意,可以在Internet Explorer(以及其他不支持indexOf的浏览器)中的数组中添加类似的功能,正如Google快速搜索所显示的(例如,这一个)。