JS: Array.prototype.includes
New in JS2016.
Array.prototype.includes
arrayX.includes(searchElement)
-
Return
true
if searchElement is in arrayX. Else,false
. arrayX.includes(searchElement, fromIndex)
- Begin search at fromIndex.
[3,4,5].includes (4)
NaN example:
[3,NaN,5].includes(NaN)
undefined example:
[3,undefined,5].includes(undefined)
Sparse Array example:
const arr = [3,4]; arr.length = 100; // make it a sparse array, lots of non-existent elements // includes will consider non-existent element as undefined console.log( arr.includes(undefined) ); // true // indexOf will consider non-existent element as undefined console.log( arr.indexOf ( undefined ) === -1 ); // true // it returns -1, which means not found
What's the difference between includes vs indexOf
The includes
method differs from
Array.prototype.indexOf
in two ways.