Using Array.map with new Array constructor

ぃ、小莉子 提交于 2019-11-28 11:44:50

You can use Array#from to create an array having passed length.

Array.from({length: 12}, (e, i) => i + 1);

Section 22.1.3.15 of the spec is getting you, with the last line of NOTE 1:

callbackfn is called only for elements of the array which actually exist; it is not called for missing elements of the array.

This behavior is shared by filter, forEach, and the other functional methods.

The array constructor you are calling, Array(len) from section 22.1.1.2, will set the length of the array but not initialize the elements. I'm not sure where the spec defines what a missing element is, but the array produced by new Array(len) should fit that and so none of the elements will be touched by map.

I like this approach because it still works in ES5:

let arr = Array.apply(null, Array(12))
    .map(function (x, i) {
        return i
    });

// [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]

Since New Array returns an array that contains "holes", we use apply because apply treats holes as if they were undefined. This spreads undefined across the entire array which makes it mappable.

You could use Array.apply with an object with the length in it.

var array = Array.apply(null, { length: 12 }).map((_, i) => i + 1);
console.log(array);

If I am not mistaken, you explicitly said that you wanted an answer with new Array constructor.

Here is how to do it. One line, beautiful ES6:

let me = [...new Array(5)].map((x,i)=>i)
// [0,1,2,3,4]

Explanation:

  1. new Array(5) generates this: [ , , , , ]​​​​​
  2. [...new Array(5)] is a shorthand for Array.from(new Array(5)), and generates this: ​​​​​[ undefined, undefined, undefined, undefined, undefined ]​​​​​, that is an array of undefined objects. Yes, undefined is a value (a primitive one :) ).
  3. Now we can iterate over the values of our brand new array :D

PS: you can even skip the new keyword and do:

[...Array(5)].map((x,i)=>i)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!