JS: Array-Like Object
What is a array-like object
A object such that Array.isArray(obj) returns false.
typically, array-like object is a normal data object with a length property, and property keys of 0, 1, 2 etc, so it looks like an array.
typically the "length" property has the Enumerable attribute false.
Create a array-like object
// simplest array-like object let xx = { length: 2 }; console.log(xx); // { length: 2 }
// create array-like object let xx = { 0: "a", 1: "b", length: 2 }; // optional Reflect.defineProperty(xx, "length", { enumerable: false }); console.log(xx); // { "0": "a", "1": "b" }
Difference between array vs array-like object
Check if a object is true array
Where does array-like object came from
- the arguments object is a array-like object.
- In web browser, method such as
document.getElementsByClassNamereturn array-like objects. [see Get Element by ID, Name, Class etc] new String("abc")creates a array-like object. [see String Constructor]
Convert array-like object to array
Array-like object is a major wart in javascript
It is a JavaScript design warts.
whenever you see it, best is to convert it to true array right away.