JavaScript: Array.prototype.includes
New in JS2016.
arrayX.includes(searchElement)
-
Return
true
if searchElement is in arrayX. Else,false
. arrayX.includes(searchElement, fromIndex)
- Begin search at fromIndex.
The includes
method differs from
Array.prototype.indexOf
in two ways.
includes
uses the SameValueZero algorithm for equality test, instead of Strict Equality Comparison, allowing it to detect NaN.includes
does not skip missing array elements, instead treating them as undefined.
console.log( [3,4,5].includes (4) ); // true
NaN example:
console.log( [3,NaN,5].includes(NaN) ); // true
undefined example:
console.log( [3,undefined,5].includes(undefined) ); // true
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