best way to generate empty 2D array

前端 未结 10 1108
伪装坚强ぢ
伪装坚强ぢ 2020-12-01 07:03

is there a shorter, better way to generate \'n\' length 2D array?

var a = (function(){ var i=9, arr=[]; while(i--) arr.push([]); return arr })();

a // [ [],         


        
相关标签:
10条回答
  • 2020-12-01 07:09

    Just discovered another ES6 way with one line expression:

    Array.from({length: N}, () => [])
    

    Array.from(arrayLike[, mapFn[, thisArg]])

    More detail about its implementation/polyfill ⇢ MDN Array.from()

    Yet another neat solution with help of array spread syntax:

    [...Array(N)].map(() => [])
    
    0 讨论(0)
  • 2020-12-01 07:13
    for(var i=9,a=[];i>=0;i--){ a.push([]) }
    
    0 讨论(0)
  • 2020-12-01 07:16

    shorter way can be :

    for(var i=9,a=[];i>=0;i--){ a.push([]) }
    
    0 讨论(0)
  • 2020-12-01 07:18
    Array(cardinality).fill(0).map(function(item) {return [];});
    

    where cardinality is the number of items you are looking at. In this case it would be 9. This was suggested by one of my colleagues actually. This is neat, I think :) This is valid from ECMA V6. Documentation: Array::fill

    0 讨论(0)
  • 2020-12-01 07:18
    var a = []; for(var i=0;i<10;i++) { a[i] = []; }
    
    0 讨论(0)
  • 2020-12-01 07:20
    var a = [];
    var max_length = 10;
    for(var i = 0; i < max_length; ++i){ 
        a[i] = []; 
    }
    
    0 讨论(0)
提交回复
热议问题