According to the MDN documentation for new Array(length)
I can initialize an array with a given length as such:
var a = new Array(10); a.length; // => 10 a; // => [undefined x 10]
However, apparently I can't use methods such as map(...)
on the new array, even though arrays constructed in other ways work fine:
a.map(function() { return Math.random(); }); // => [undefined x 10] -- wtf? [undefined, undefined].map(function() { return Math.random(); }); // => [0.07192076672799885, 0.8052175589837134]
Why is this the case?
I understand from this experience (and searching the web) that the array constructor with length is a black hole of unexplained behavior, but does the ECMA 262 specification offer an explanation?
Arrays are Objects Arrays are a special type of objects. The typeof operator in JavaScript returns "object" for arrays. But, JavaScript arrays are best described as arrays.
The length property of an object which is an instance of type Array sets or returns the number of elements in that array. The value is an unsigned, 32-bit integer that is always numerically greater than the highest index in the array.
splice alters the length of an array.
We can extend the standard Array class and add new methods or redefine the existing ones. The of method on the new extended class creates a new extended array. The standard array methods like filter and map called on extended array return extended arrays.
new Array(10)
doesn't return an array filled with 10 undefined
s. Instead, it returns an array with no elements, and with a length
property of 10
.
See the difference:
var arr1 = new Array(1), arr2 = [undefined]; arr1.length === arr2.length; // Both are `1` arr1[0] === arr2[1]; // Both are `undefined` arr1.hasOwnProperty(0); // false arr2.hasOwnProperty(0); // true
Therefore, ECMAScript 5 array methods skip those non-existing properties. Specifically, when they iterate from 0
to length
, they check the [[HasProperty]]
internal method of the array.
You can fix it easily with ECMAScript 6 Array.prototype.fill
(which can be polyfilled):
new Array(10).fill().map(Math.random);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With