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

后端 未结 6 605
误落风尘
误落风尘 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:25

    Very simple function, generate an array with any number of dimensions. Specify length of each dimension and the content which for me is '' usually

    function arrayGen(content,dims,dim1Len,dim2Len,dim3Len...) {
      var args = arguments;
      function loop(dim) {
        var array = [];
        for (var a = 0; a < args[dim + 1]; a++) {
          if (dims > dim) {
            array[a] = loop(dim + 1);
          } else if (dims == dim) {
            array[a] = content;
          }
        }
        return array;
      }
      var  thisArray = loop(1);
      return thisArray;
    };
    

    I use this function very often, it saves a lot of time

提交回复
热议问题