Array constructor not working properly

I want to create an empty array with a fixed length, and then use .map on it to return a new array. However, it does not work properly.

According to mdn docs :

If the only argument passed to the Array constructor is an integer from 0 to 232-1 (inclusive), this returns a new JavaScript array with the length set for that number.

new Array(3) returns [undefined × 3] . Shouldn't be: [undefined, undefined, undefined] ?

Consider the following examples:

1) Doesn't work.

 var a = new Array(3); a.map((x, i) => i); // [undefined × 3] 

2) Work.

 var a = Array.apply(null, new Array(3)); a.map((x, i) => i); // [0, 1, 2] 

I tested this on the latest version of Google Chrome Canary.

+7
javascript
source share
3 answers

From MDN : this returns a new JavaScript array with length set to that number

The array created by new Array(n) has no elements, but only lengths. This is why you cannot match (non existing) elements.

+3
source share

map skips undefined elements by design.

From the documentation :

callback is called only for array indices assigned values

There are many SO questions related to this topic, and providing ways to create arrays that will be displayed in all elements, such as

 new Array(3) . fill() . map(... 

take just one example using the new Array # fill method.

+1
source share

Example in addition to CodeiSirs:

 // foo and bar are identical. They are arrays with length 3 and no indices. var foo = new Array(3); var bar = []; bar.length = 3; console.log(foo); console.log(bar); // This is different. It has 3 indices with the value undefined. var pez = [undefined, undefined, undefined]; console.log(pez); 

The console displays new Array(3) somehow weird because it's not the same as [undefined, undefined, undefined]

0
source share

All Articles