best way to generate empty 2D array

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

    Another way:

    for(var a = [];a.length < 10; a.push([])); // semicolon is mandatory here
    

    Yet another way:

    var a = []; while(a.push([]) < 10);
    

    This works because .push() [docs] (specification) returns the new length of the array.


    That said, this is the wrong way of "reducing code". Create a dedicated function with a meaningful name and use this one. Your code will be much more understandable:

    function get2DArray(size) {
        size = size > 0 ? size : 0;
        var arr = [];
    
        while(size--) {
            arr.push([]);
        }
    
        return arr;
    }
    
    var a = get2DArray(9);
    

    Code is read much more often than written.

提交回复
热议问题