Array.prototype.includes()
El mètode includes()
determina si un array inclou un element concret, retornant true
o false
segons s'escaigui.
Sintaxi
var boolean = array.includes(elementCercat[, desdePosicio])
Parameters
- elementCercat
- L'element a cercar.
- desdePosicio
- Opcional. La posició de l'array a partir de la qual començar la cerca de
elementCercat
. Un valor negatiu cercarà el nombre absolut donat de posicions contant des del final de l'array. El seu valor per defecte és 0.
Valor retornat
Un Boolean
.
Exemples
[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
if (!Array.prototype.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)) { // NaN !== NaN
return true;
}
k++;
}
return false;
};
}
Especificacions
Especificació | Estat | Comentaris |
---|---|---|
ECMAScript 2016 (ECMA-262) The definition of 'Array.prototype.includes' in that specification. |
Standard | Definició inicial. |
ECMAScript (ECMA-262) The definition of 'Array.prototype.includes' in that specification. |
Living Standard |
Compatibilitat amb navegadors
We're converting our compatibility data into a machine-readable JSON format.
This compatibility table still uses the old format,
because we haven't yet converted the data it contains.
Find out how you can help! (en-US)
Característica | Chrome | Firefox (Gecko) | Internet Explorer | Edge | Opera | Safari |
---|---|---|---|---|---|---|
Suport bàsic |
47 |
43 | No support | No support | 34 | 9 |
Característica | Android | Android Webview | Firefox Mobile (Gecko) | IE Mobile | Opera Mobile | Safari Mobile | Chrome for Android |
---|---|---|---|---|---|---|---|
Suport bàsic | No support |
47 |
43 | No support | 34 | 9 |
47 |