Signatur
Beschreibung
Die statische Methode Array.isArray() ermittelt, ob der übergebene Wert ein Array ist.
Array.isArray() prüft, ob der übergebene Wert ein Array ist. Sie führt eine branded check durch, ähnlich dem in-Operator, für ein privates Feld, das vom Array()-Konstruktor initialisiert wird.
Sie ist eine robustere Alternative zu instanceof Array, da sie sowohl falsch positive als auch falsch negative Ergebnisse vermeidet:
Array.isArray()weist Werte zurück, die keine echtenArray-Instanzen sind, selbst wenn sieArray.prototypein ihrer Prototype-Chain haben —instanceof Arraywürde diese akzeptieren, da es die Prototype-Chain prüft.Array.isArray()akzeptiertArray-Objekte, die in einem anderen Realm konstruiert wurden —instanceof Arraygibt für diesefalsezurück, weil die Identität desArray-Konstruktors sich zwischen Realms unterscheidet.
Weitere Details finden Sie im Artikel „Determining with absolute accuracy whether or not a JavaScript object is an array".
Parameter
| Name | Typ | Default | Beschreibung |
|---|---|---|---|
| $value Pflicht | any | — | Der zu prüfende Wert. |
Rückgabewert
true, wenn value ein Array ist; andernfalls false. false wird immer zurückgegeben, wenn value eine TypedArray-Instanz ist.Beispiele
Verwendung von Array.isArray()
// all following calls return true
Array.isArray([]);
Array.isArray([1]);
Array.isArray(new Array());
Array.isArray(new Array("a", "b", "c", "d"));
Array.isArray(new Array(3));
// Little known fact: Array.prototype itself is an array:
Array.isArray(Array.prototype);
// all following calls return 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(new Uint8Array(32));
// This is not an array, because it was not created using the
// array literal syntax or the Array constructor
Array.isArray({ __proto__: Array.prototype });
instanceof vs. Array.isArray()
const iframe = document.createElement("iframe");
document.body.appendChild(iframe);
const xArray = window.frames[window.frames.length - 1].Array;
const arr = new xArray(1, 2, 3); // [1, 2, 3]
// Correctly checking for Array
Array.isArray(arr); // true
// The prototype of arr is xArray.prototype, which is a
// different object from Array.prototype
arr instanceof Array; // false