Array.prototype.fill() with object passes reference and not new instance

后端 未结 6 1433
陌清茗
陌清茗 2020-11-22 03:57

I was toying a bit and was trying to instantiate a new array of length x, where all elements of that array were initialized to a value y:

         


        
相关标签:
6条回答
  • 2020-11-22 04:13

    Ilias Karim's answer is most excellent. I just did the following:

    a = Array.from({length:l}, () => new Array(c).fill(prefix));
    

    to create a pre-filled 2D array of the specified size, l by c, filled with prefix. Now my code can fill in the slots in the 2D matrix that need non-prefix values.

    0 讨论(0)
  • 2020-11-22 04:17

    Shortest Possable:

    let node =  [...Array(2)].map(_=>({}))
    console.log(node)

    0 讨论(0)
  • 2020-11-22 04:18

    You could also solve this by the following workaround.

    var arr = new Array(2).fill({});
    arr = JSON.parse(JSON.stringify(arr));
    
    0 讨论(0)
  • 2020-11-22 04:19

    One performant solution: Array.from({ length: 5 }, () => new Object())

    0 讨论(0)
  • 2020-11-22 04:20

    The accepted answer is good and would work in 90% of cases.

    But if you are making high-performance JS application, and if you work with big/huge arrays, Array.map(..) creates big overload in both - memory and processor use, as it creates a copy of an array.

    I recommend to use the classic for loop:

        a = new Array(ARRAY_SIZE);
        for (var i = 0; i < ARRAY_SIZE; i++) {
            a[i] = [];
        }
    

    I tested six alternatives and got this:

    • Array.map(), as proposed above (11x times!!! slower):

       a = new Array(ARRAY_SIZE).fill().map(u => { return []; });
      
    • for loop, the best one (fastest):

       a = new Array(ARRAY_SIZE);
       for (var i = 0; i < ARRAY_SIZE; i++) {
           a[i] = [];
       }
      
    • forEach (6x time slower):

       a = new Array(ARRAY_SIZE).fill();
       a.forEach((val, i) => {
           a[i] = [];
       })
      

    [UPDATE 2020-08-27] One more way proposed by Ilias Karim below

    • Array.from (30x times!!! slower) - apparently worse in terms of performance, despite the nicest syntax :(

       a = Array.from({ length: ARRAY_SIZE }, () => []);
      
    • [..Array(..)] (5x times!!! slower)

       a = [...Array(ARRAY_SIZE)].map(_=>([]))
      
    • Array.push(..), second place in terms of performance (2x times!!! slower)

       let a = [], total = ARRAY_SIZE;
       while(total--) a.push([]);
      

    PS. I used this fiddle for tests.

    0 讨论(0)
  • 2020-11-22 04:27

    You can first fill the array with any value (e.g. undefined), and then you will be able to use map:

    var arr = new Array(2).fill().map(u => ({}));
    
    var arr = new Array(2).fill().map(Object);
    
    0 讨论(0)
提交回复
热议问题