Disclaimer: Creating array-like objects is not recommend. However, it is helpful to understand how they work, especially when working with DOM. This will explain why regular array operations don't work on DOM objects returned from many DOM
document
functions. (i.e.querySelectorAll
,form.elements
)
Supposing we created the following object which has some properties you would expect to see in an Array.
var anObject = {
foo: 'bar',
length: 'interesting',
'0': 'zero!',
'1': 'one!'
};
Then we'll create an array.
var anArray = ['zero.', 'one.'];
Now, notice how we can inspect both the object, and the array in the same way.
console.log(anArray[0], anObject[0]); // outputs: zero. zero!
console.log(anArray[1], anObject[1]); // outputs: one. one!
console.log(anArray.length, anObject.length); // outputs: 2 interesting
console.log(anArray.foo, anObject.foo); // outputs: undefined bar
Since anArray
is actually an object, just like anObject
, we can even add custom wordy properties to anArray
Disclaimer: Arrays with custom properties are not usually recommended as they can be confusing, but it can be useful in advanced cases where you need the optimized functions of an Array. (i.e. jQuery objects)
anArray.foo = 'it works!';
console.log(anArray.foo);
We can even make anObject
to be an array-like object by adding a length
.
anObject.length = 2;
Then you can use the C-style for
loop to iterate over anObject
just as if it were an Array. See Array Iteration
Note that anObject
is only an array-like object. (also known as a List) It is not a true Array. This is important, because functions like push
and forEach
(or any convenience function found in Array.prototype
) will not work by default on array-like objects.
Many of the DOM document
functions will return a List (i.e. querySelectorAll
, form.elements
) which is similar to the array-like anObject
we created above. See Converting Array-like Objects to Arrays
console.log(typeof anArray == 'object', typeof anObject == 'object'); // outputs: true true
console.log(anArray instanceof Object, anObject instanceof Object); // outputs: true true
console.log(anArray instanceof Array, anObject instanceof Array); // outputs: true false
console.log(Array.isArray(anArray), Array.isArray(anObject)); // outputs: true false