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

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

提交回复
热议问题