best way to generate empty 2D array

前端 未结 10 1277
伪装坚强ぢ
伪装坚强ぢ 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: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

提交回复
热议问题