Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is a new JavaScript array with length unusable? [duplicate]

Tags:

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?

like image 653
maerics Avatar asked Feb 06 '15 17:02

maerics


People also ask

What is new array in JavaScript?

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.

What property tells you the length of a JavaScript array?

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.

Does splice change array length?

splice alters the length of an array.

Can JavaScript arrays be extended?

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.


1 Answers

new Array(10) doesn't return an array filled with 10 undefineds. 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); 
like image 58
Oriol Avatar answered Nov 03 '22 09:11

Oriol