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

后端 未结 14 2086
粉色の甜心
粉色の甜心 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条回答
  •  Happy的楠姐
    2020-11-22 03:29

    For reasons thoroughly explained in other answers, Array(n).map doesn't work. However, in ES2015 Array.from accepts a map function:

    let array1 = Array.from(Array(5), (_, i) => i + 1)
    console.log('array1', JSON.stringify(array1)) // 1,2,3,4,5
    
    let array2 = Array.from({length: 5}, (_, i) => (i + 1) * 2)
    console.log('array2', JSON.stringify(array2)) // 2,4,6,8,10

提交回复
热议问题