找出JavaScript数组是否包含值的最简洁有效的方法是什么?
这是我知道的唯一方法:
function contains(a, obj) {
for (var i = 0; i < a.length; i++) {
if (a[i] === obj) {
return true;
}
}
return false;
}
有没有更好、更简洁的方法来实现这一点?
这与堆栈溢出问题密切相关。在JavaScript数组中查找项目的最佳方法是什么?它解决了使用indexOf查找数组中的对象的问题。
复杂性O(n/2)
您可以使用任何库函数,但我使用的是核心JavaScript。如果返回true,我们首先搜索中间的元素,否则我们同时从左到中和从右到中搜索数组中的元素。因此,它将具有O(n/2)复杂性。并且它将返回true或false,指示它是否存在
let isExist = (arr, element)=> {
let index = -1;
if ((arr.length % 2 != 0) && arr[(arr.length-1)/2]===element) {
index = 1;
return true;
}
for(let i=0; i<Math.ceil(arr.length-1/2); i++){
if (arr[i]===element || (arr[arr.length-i]===element)) {
index = i;
break;
}
}
return (index<0)? false : true;
}
let array = ['apple', 'ball', 'cat', 'dog', 'egg']
console.log(isExist(array, 'yellow'));
//Result false because yellow doesn't exist in array
console.log(isExist(array, 'cat'));
//Result true because yellow exist in array
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
它可以是多填充的,以使其在所有浏览器上都可以使用。
除了其他人所说的之外,如果没有要在数组中搜索的对象的引用,那么可以执行类似的操作。
let array = [1, 2, 3, 4, {"key": "value"}];
array.some((element) => JSON.stringify(element) === JSON.stringify({"key": "value"})) // true
array.some((element) => JSON.stringify(element) === JSON.stringify({})) // true
如果任何元素与给定条件匹配,Array.some返回true;如果没有元素与给定的条件匹配,则返回false。
现代浏览器具有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(值,数组)
请注意,一些框架将其作为函数实现,而另一些框架将该函数添加到数组原型中。