Array-Like Objects
As we’ve seen, JavaScript arrays have some special features that other objects do not have:
The
length
property is automatically updated as new elements are added to the list.Setting
length
to 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:
var
a
=
{};
// Start with a regular empty object
// Add properties to make it "array-like"
var
i
=
0
;
while
(
i
<
10
)
{
a
[
i
]
=
i
*
i
;
i
++
;
}
a
.
length
=
i
;
// Now iterate through it as if it were a real ...
Get JavaScript: The Definitive Guide, 6th Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.