Array.prototype.includes()
The includes()
method determines whether an array includes a certain element, returning true
or false
as appropriate.
Syntax
JavaScript
Copy Code
var <var>boolean</var> = <var>array</var>.includes(<var>searchElement</var>[, <var>fromIndex</var>])
Parameters
searchElement
- The element to search for.
fromIndex
- Optional. The position in this array at which to begin searching for
searchElement
. A negative value searches from the index of array.length + fromIndex by asc. Defaults to 0.
Return value
A Boolean
.
Examples
JavaScript
Copy Code
[1, 2, 3].includes(2); // true [1, 2, 3].includes(4); // false [1, 2, 3].includes(3, 3); // false [1, 2, 3].includes(3, -1); // true [1, 2, NaN].includes(NaN); // true
Polyfill
JavaScript
Copy Code
if (!Array.prototype.includes) { Array.prototype.includes = function(searchElement /*, fromIndex*/) { 'use strict'; if (this == null) { throw new TypeError('Array.prototype.includes called on null or undefined'); } var O = Object(this); var len = parseInt(O.length, 10) || 0; if (len === 0) { return false; } var n = parseInt(arguments[1], 10) || 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)) { // NaN !== NaN return true; } k++; } return false; }; }
Specifications
Specification | Status | Comment |
---|---|---|
ECMAScript 2016 (ECMA-262) The definition of 'Array.prototype.includes' in that specification. |
Standard | Initial definition. |
ECMAScript 2017 Draft (ECMA-262) The definition of 'Array.prototype.includes' in that specification. |
Draft |
Browser compatibility
Feature | Chrome | Firefox (Gecko) | Internet Explorer | Edge | Opera | Safari |
---|---|---|---|---|---|---|
Basic support |
47 |
43 | No support | 14279+ | 34 | 9 |
Feature | Android | Android Webview | Firefox Mobile (Gecko) | IE Mobile | Opera Mobile | Safari Mobile | Chrome for Android |
---|---|---|---|---|---|---|---|
Basic support | No support |
47 |
43 | No support | 34 | 9 |
47 |
See also
License
© 2016 Mozilla Contributors
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
https://developer.mozilla.org/en-us/docs/web/javascript/reference/global_objects/array/includes