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

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

    0 讨论(0)
  • 2020-12-10 13:29

    The more dimension you have, the more you have interest in using one single flat array and a getter /setter function for your array.
    Because for a [d1 X d2 X d3 X .. X dn] you'll be creating d2*d3*...*dn arrays instead of one, and when accessing, you'll make n indirection instead of 1.

    The interface would look like :

    var myNArray = new NArray(10,20,10);
    var oneValue = myNArray.get(5,8,3);
    myNArray.set(8,3,2, 'the  value of (8,3,2)');
    

    the implementation depends on your preference for a fixed-size n-dimensionnal array or an array able to push/pop and the like.

    0 讨论(0)
  • 2020-12-10 13:31

    Adapted from this answer:

    function createArray(length) {
      var arr = new Array(length || 0),
          i = length;
        
      if (arguments.length > 1) {
        var args = Array.prototype.slice.call(arguments, 1);
        while(i--) arr[i] = createArray.apply(this, args);
      }        
      return arr;
     }
    

    Simply call with an argument for the length of each dimension. Usage examples:

    • var multiArray = createArray(10,10,10); Gives a 3-dimensional array of equal length.
    • var weirdArray = createArray(34,6,42,2); Gives a 4-dimensional array of unequal lengths.
    0 讨论(0)
  • 2020-12-10 13:31
    function multiDimArrayInit(dimensions, leafValue) {
        if (!dimensions.length) {
            return leafValue;
        }
        var arr = [];
        var subDimensions = dimensions.slice(1);
        for (var i = 0; i < dimensions[0]; i++) {
            arr.push(multiDimArrayInit(subDimensions, leafValue));
        }
        return arr;
    }
    
    
    console.log(multiDimArrayInit([2,8], "hi")); // counting the nested "hi"'s yields 16 of them
    

    demo http://jsfiddle.net/WPrs3/

    0 讨论(0)
  • 2020-12-10 13:38

    A more succinct version of @chris code:

    function multiDim (dims, leaf) {
      dims = Array.isArray (dims) ? dims.slice () : [dims];
      return Array.apply (null, Array (dims.shift ())).map (function (v, i) {
        return dims.length 
          ? multiDim (dims, typeof leaf == 'string' ? leaf.replace ('%i', i + ' %i') : leaf)
          : typeof leaf == 'string' ? leaf.replace ('%i', i) : leaf;
      });      
    }
    
    console.log (JSON.stringify (multiDim ([2,2], "hi %i"), null, '  ')); 
    

    Produces :

    [
      [
        "hi 0 0",
        "hi 0 1"
      ],
      [
        "hi 1 0",
        "hi 1 1"
      ]
    ]
    

    In this version you can pass the first argument as a number for single dimension array. Including %i in the leaf value will provide index values in the leaf values.

    Play with it at : http://jsfiddle.net/jstoolsmith/r3eMR/

    0 讨论(0)
  • 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<arguments[0];i++) {
            arr[i] = (arguments.length > 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/

    0 讨论(0)
提交回复
热议问题