JS: Array.prototype.includes
(new in ECMAScript 2016)
Array.prototype.includes
xArray.includes(searchElement)-
Return
trueif searchElement is in xArray. Else,false.console.log([3, 4, 5].includes(4)); // true xArray.includes(searchElement, fromIndex)-
Begin search at fromIndex, can be negative.
console.log(["x", 4, 5].includes("x", 0)); // true console.log(["x", 4, 5].includes("x", 1)); // false // negative index, search start at end console.log([3, 4, 5].includes(3, -1)); // false
Example
On NaN
console.log([3, NaN, 5].includes(NaN));
On undefined
console.log([3, undefined, 5].includes(undefined));
On Sparse Array
const xx = [3, 4]; // make it a sparse array xx.length = 100; // includes finds non-existent element console.log(xx.includes(undefined)); // true
What's the difference between includes vs indexOf
Array.prototype.indexOf:
- Return the index.
- Cannot detect NaN.
- Skip missing index in sparse array.
Array.prototype.includes: