Object vs Array in JavaScript
Mit typeof lässt sich nicht eindeutig bestimmen, ob eine Variable ein Array oder ein Object ist.
typeof []; // Returns "object"
typeof {}; // Returns "object"
typeof {}; // Returns "object"
Am elegantesten finde ich bis jetzt die Lösung über den Prototype von Object:
Object.prototype.toString.call([]); // Returns "[object Array]"
Object.prototype.toString.call({}); // Returns "[object Object]"
Object.prototype.toString.call({}); // Returns "[object Object]"
Beispielhaft angewendet:
if (!Object.prototype.toString.call(myVar) === "[object Array]") {
throw "myVar muss ein Array sein";
}
throw "myVar muss ein Array sein";
}