When it comes to JavaScript, arrays have their own unique quirks that set them apart from other programming languages.
Take this example:
// Creating a regular array.
var regularArray = [];
regularArray.length = 0;
regularArray.push(1);
regularArray[1] = 2;
regularArray; // returns [1, 2]
regularArray.length // returns 2
We all know how to create and populate arrays like the above, right? (let's ignore the normalArray.length = 0
for now)
But what happens when we try the same process on an object that is not purely an array? The outcome looks slightly different, with the length
property being somewhat inaccurate.
// Creating an object that inherits from the array prototype (i.e.: custom array)
var customArray = new (function MyArray() {
this.__proto__ = Object.create(Array.prototype);
return this
});
customArray.length = 0;
customArray.push(1);
customArray[1] = 2;
customArray; // returns [1, 1: 2]
customArray.length // returns 1
The behavior here is puzzling, so any help in understanding it would be greatly appreciated.