Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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 initialize an empty 10x10x10 array using var theArray = new Array(10, 10 10), but instead, it only created a 1-dimensional array with 3 elements.

I've figured out how to initialize an empty 10x10x10 array using nested for-loops, but it's extremely tedious to write the array initializer this way. Initializing multidimensional arrays using nested for-loops can be quite tedious: is there a more concise way to set the dimensions of empty multidimensional arrays in JavaScript (with arbitrarily many dimensions)?

//Initializing an empty 10x10x10 array:
var theArray = new Array();
for(var a = 0; a < 10; a++){
    theArray[a] = new Array();
    for(var b = 0; b < 10; b++){
        theArray[a][b] = new Array();
        for(var c = 0; c < 10; c++){
            theArray[a][b][c] = 10
        }
    }
}

console.log(JSON.stringify(theArray));
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
388 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...