best way to generate empty 2D array

前端 未结 10 1233
伪装坚强ぢ
伪装坚强ぢ 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(() => [])
    

提交回复
热议问题