Check if an element is present in an array
This question already has an answer here:
ECMAScript 2016 incorporates an includes()
method for arrays that specifically solves the answer, and so is now the preferred method. (As of June 2016 you will need to use a polyfill until the method is implemented natively in all major browsers.)
[1, 2, 3].includes(2); // true
[1, 2, 3].includes(4); // false
[1, 2, 3].includes(3, 3); // false
Code:
function isInArray(value, array) {
return array.indexOf(value) > -1;
}
Execution:
isInArray(1, [1,2,3]); // true
Update (2017):
In modern browsers with ECMAScript 6 support you can use the function Array.prototype.includes, which makes it way more easier to check if an item is present in an array:
const haystack = [1, 2, 3];
const needle = 1;
const isInArray = haystack.includes(needle);
console.log(isInArray); // true
Just use indexOf
:
haystack.indexOf(needle) >= 0
If you want to support old Internet Explorers (< IE9), you'll have to include your current code as a workaround though.
Unless your list is sorted, you need to compare every value to the needle. Therefore, both your solution and indexOf
will have to execute n/2
comparisons on average. However, since indexOf
is a built-in method, it may use additional optimizations and will be slightly faster in practice. Note that unless your application searches in lists extremely often (say a 1000 times per second) or the lists are huge (say 100k entries), the speed difference will not matter.
上一篇: 如何检查一个字符串数组是否包含JavaScript中的一个字符串?
下一篇: 检查数组中是否存在元素