JS: Array-Like Object
What is a array-like object
A object such that is all of the following:
Array.isArray(obj)returnsfalse.- Has a property
"length"with value of non-negative integer, and typically it has the Enumerable attribute false. - Typically has property names of non-negative string integers {
"0","1","2", etc} up to the length -1.
Create a Array-Like Object
// create array-like object let xx = { 0: "a", 1: "b", length: 2 }; 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
- 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〕
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.