Array.prototype.includes()
In ES2016, there is Array.prototype.includes().
The includes()
method determines whether an array includes a certain element, returning true
or false
as appropriate.
Example
["Sam", "Great", "Sample", "High"].includes("Sam"); // true
Support
According to kangax and MDN, the following platforms are supported:
- Chrome 47
- Edge 14
- Firefox 43
- Opera 34
- Safari 9
- Node 6
Support can be expanded using Babel (using babel-polyfill
) or core-js. MDN also provides a polyfill:
if (![].includes) {
Array.prototype.includes = function(searchElement /*, fromIndex*/ ) {
'use strict';
var O = Object(this);
var len = parseInt(O.length) || 0;
if (len === 0) {
return false;
}
var n = parseInt(arguments[1]) || 0;
var k;
if (n >= 0) {
k = n;
} else {
k = len + n;
if (k < 0) {k = 0;}
}
var currentElement;
while (k < len) {
currentElement = O[k];
if (searchElement === currentElement ||
(searchElement !== searchElement && currentElement !== currentElement)) {
return true;
}
k++;
}
return false;
};
}