Array-Like Objects
As we’ve seen, JavaScript arrays have some special features that other objects do not have:
The
lengthproperty is automatically updated as new elements are added to the list.Setting
lengthto a smaller value truncates the array.Arrays inherit useful methods from
Array.prototype.Arrays have a class attribute of “Array”.
These are the features that make JavaScript arrays distinct from
regular objects. But they are not the essential features that define
an array. It is often perfectly reasonable to treat any object with a
numeric length property and
corresponding non-negative integer properties as a kind of
array.
These “array-like” objects actually do occasionally appear in
practice, and although you cannot directly invoke array methods on
them or expect special behavior from the length property, you can still iterate
through them with the same code you’d use for a true array. It turns
out that many array algorithms work just as well with array-like
objects as they do with real arrays. This is especially true if your
algorithms treat the array as read-only or if they at least leave the
array length unchanged.
The following code takes a regular object, adds properties to make it an array-like object, and then iterates through the “elements” of the resulting pseudo-array:
vara={};// Start with a regular empty object// Add properties to make it "array-like"vari=0;while(i<10){a[i]=i*i;i++;}a.length=i;// Now iterate through it as if it were a real ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access