Is there a more concise way to initialize empty multidimensional arrays?

后端 未结 6 617
误落风尘
误落风尘 2020-12-10 13:06

I\'ve been trying to find a reasonably concise way to set the dimensions of an empty multidimensional JavaScript array, but with no success so far.

First, I tried to

6条回答
  •  轮回少年
    2020-12-10 13:41

    Here is my take on the problem: nArray utility function

    function nArray() {
        var arr = new Array();
        var args = Array.prototype.slice.call(arguments, 1);
        for(var i=0;i 1 && nArray.apply(this, args)) || undefined;
        }
        return arr;
    }
    

    Usage example:

    var arr = nArray(3, 3, 3);
    

    Results in 3x3x3 array of undefined values.

    Running code with some tests also available as a Fiddle here: http://jsfiddle.net/EqT3r/7/

提交回复
热议问题