Array-Like Objects
Array‑like objects are objects that have a length property and indexed elements but do not have array methods. Common examples include the arguments object, HTML collections (like NodeList), and strings. They can be converted to real arrays using Array.from() or Array.prototype.slice.call().
Key Points
Section titled “Key Points”- They have numeric indices and a
lengthproperty. - They do not inherit from
Array.prototype, so they lack methods likemap,filter. - You can access elements using bracket notation.
Code Example
Section titled “Code Example”// An array-like objectconst arrayLike = { 0: "a", 1: "b", 2: "c", length: 3,};
console.log(arrayLike[0]); // "a"console.log(arrayLike.length); // 3
// But cannot use array methods// arrayLike.forEach is undefined
// Convert to arrayconst realArray = Array.from(arrayLike);console.log(realArray); // ["a", "b", "c"]
// Alternative: sliceconst anotherArray = Array.prototype.slice.call(arrayLike);console.log(anotherArray); // ["a", "b", "c"]