更新时间:2022-11-01 09:32:39
现代浏览器有 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
,它不太直接,但不需要为过时的浏览器提供 polyfill.
You can also use Array#indexOf
, which is less direct, but doesn't require polyfills for outdated browsers.
console.log(['joe', 'jane', 'mary'].indexOf('jane') >= 0); //true
许多框架也提供了类似的方法:
Many frameworks also offer similar methods:
$.inArray(value, array, [fromIndex])
_.contains(array, value)
(也别名为 _.include
和 _.includes
)dojo.indexOf(array, value, [fromIndex, findLast])
array.indexOf(value)
一个>
array.indexOf(value)
findValue(array, value)
array.indexOf(value)代码>
Ext.Array.contains(array, value)
_.includes(array, value, [from])
(是 _.contains
之前的 4.0.0)R.includes(value, array)
莉>
$.inArray(value, array, [fromIndex])
_.contains(array, value)
(also aliased as _.include
and _.includes
)dojo.indexOf(array, value, [fromIndex, findLast])
array.indexOf(value)
array.indexOf(value)
findValue(array, value)
array.indexOf(value)
Ext.Array.contains(array, value)
_.includes(array, value, [from])
(is _.contains
prior 4.0.0)R.includes(value, array)
请注意,一些框架将其实现为一个函数,而另一些框架则将该函数添加到数组原型中.
Notice that some frameworks implement this as a function, while others add the function to the array prototype.