La méthode Array.isArray() permet de déterminer si l'objet passé en argument est un objet Array, elle renvoie true si le paramètre passé à la fonction est de type Array et false dans le cas contraire.
Array.isArray([1, 2, 3]); // true
Array.isArray({toto: 123}); // false
Array.isArray("tototruc"); // false
Array.isArray(undefined); // false
Syntaxe
Array.isArray(obj)
Paramètres
obj- L'objet dont on veut vérifier le type
Valeur de retour
true si l'objet est un tableau (instance de Array), false sinon.
Description
Si l'objet indiqué en paramètre est un Array, la méthode renvoie true, sinon, elle renvoie false.
Voir aussi : « Determining with absolute accuracy whether or not a JavaScript object is an array » (en anglais) pour avoir plus de détails.
Exemples
// tout les appels suivant renvoient true
Array.isArray([]);
Array.isArray([1]);
Array.isArray( new Array() );
// Une petite anecdote: Array.prototype lui même est un Array
Array.isArray( Array.prototype );
// tout les appels suivant renvoient false
Array.isArray();
Array.isArray({});
Array.isArray(null);
Array.isArray(undefined);
Array.isArray(17);
Array.isArray("Array");
Array.isArray(true);
Array.isArray(false);
Array.isArray({ __proto__ : Array.prototype });
Prothèse d'émulation (polyfill)
Exécuter ce code avant tout les autres aboutira à la création de la méthode Array.isArray()si elle n'est pas nativement prise en charge par le navigateur.
if(!Array.isArray) {
Array.isArray = function(arg) {
return Object.prototype.toString.call(arg) === '[object Array]';
};
}
Spécifications
| Spécification | État | Commentaires |
|---|---|---|
| ECMAScript 5.1 (ECMA-262) La définition de 'Array.isArray' dans cette spécification. |
Standard | Définition initiale. Implémentée avec JavaScript 1.8.5. |
| ECMAScript 2015 (6th Edition, ECMA-262) La définition de 'Array.isArray' dans cette spécification. |
Standard | |
| ECMAScript 2017 Draft (ECMA-262) La définition de 'Array.isArray' dans cette spécification. |
Projet |
Compatibilité des navigateurs
| Fonctionnalité | Chrome | Firefox (Gecko) | Internet Explorer | Opera | Safari |
|---|---|---|---|---|---|
| Support simple | 5 | 4.0 (2.0) | 9 | 10.5 | 5 |
| Fonctionnalité | Android | Chrome pour Android | Firefox Mobile (Gecko) | IE Mobile | Opera Mobile | Safari Mobile |
|---|---|---|---|---|---|---|
| Support simple | (Oui) | (Oui) | 4.0 (2.0) | (Oui) | (Oui) | (Oui) |