Arrays are Objects
suggest changeDisclaimer: Creating array-like objects is not recommended. It is still useful to understand them, especially with the DOM. It explains why many array operations do not work on values returned by DOM methods such as
querySelectorAlland properties such asform.elements. Some host lists, includingNodeList, now implementforEach, but they are still not arrays.
Supposing we created the following object which has some properties you would expect to see in an Array.
const anObject = {
foo: 'bar',
length: 'interesting',
'0': 'zero!',
'1': 'one!'
};
Then we’ll create an array.
const 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 add non-index 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);
anObject already has a length property, but its value is a string. Setting length to a number makes the object array-like:
anObject.length = 2;
Then you can use a C-style for loop to iterate over anObject just as if it were an array. See 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 DOM APIs return a list (for example querySelectorAll or form.elements) similar to the array-like anObject 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