JavaScript “new Array(n)” and “Array.prototype.map” weirdness

后端 未结 14 2170
粉色の甜心
粉色の甜心 2020-11-22 02:40

I\'ve observed this in Firefox-3.5.7/Firebug-1.5.3 and Firefox-3.6.16/Firebug-1.6.2

When I fire up Firebug:

14条回答
  •  闹比i
    闹比i (楼主)
    2020-11-22 03:39

    I had a task that I only knew the length of the array and needed to transform the items. I wanted to do something like this:

    let arr = new Array(10).map((val,idx) => idx);
    

    To quickly create an array like this:

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

    But it didn't work because: (see Jonathan Lonowski's answer a few answers above)

    The solution could be to fill up the array items with any value (even with undefined) using Array.prototype.fill()

    let arr = new Array(10).fill(undefined).map((val,idx) => idx);
    

    console.log(new Array(10).fill(undefined).map((val, idx) => idx));

    Update

    Another solution could be:

    let arr = Array.apply(null, Array(10)).map((val, idx) => idx);
    

    console.log(Array.apply(null, Array(10)).map((val, idx) => idx));

提交回复
热议问题