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

后端 未结 8 1917
忘了有多久
忘了有多久 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.

    0 讨论(0)
  • 2020-12-03 11:15

    You can populate an array with zeros using this function:

    function fillArrayWithNumber(n) {
      var arr = Array.apply(null, Array(n));
      return arr.map(function (x, i) { return 0; });
    }
    
    fillArrayWithNumber(5); // [0,0,0,0,0]
    

    Or with a small change you can use indexes instead:

    function fillArrayWithIndex(n) {
      var arr = Array.apply(null, Array(n));
      return arr.map(function (x, i) { return i; });
    }
    
    fillArrayWithIndex(5); // [0,1,2,3,4]
    

    Fiddle

    0 讨论(0)
提交回复
热议问题