Array.map doesn't seem to work on uninitialized arrays

后端 未结 8 1970
忘了有多久
忘了有多久 2020-12-03 10:35

I\'m trying to set default values on an uninitialized array using the map function but it doesn\'t seem to work, any ideas on how to set default values?

Consider thi

8条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-03 11:11

    Building on a previous answer there is new shorter syntax. The OP wanted to create an array of N items initialized with 0.

    var N = 10;
    var x = new Array(N).fill(0);
    // x is now: [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
    

    You also don't need the new - it's optional in this context.

    Check the compatibility of your target platform and/or use a pollyfill if not available.

提交回复
热议问题