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


i've been trying find reasonably concise way set dimensions of empty multidimensional javascript array, no success far.

first, tried initialize empty 10x10x10 array using var thearray = new array(10, 10 10), instead, created 1-dimensional array 3 elements.

i've figured out how initialize empty 10x10x10 array using nested for-loops, it's extremely tedious write array initializer way. initializing multidimensional arrays using nested for-loops can quite tedious: there more concise way set dimensions of empty multidimensional arrays in javascript (with arbitrarily many dimensions)?

//initializing empty 10x10x10 array: var thearray = new array(); for(var = 0; < 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)); 

adapted this answer:

function createarray(length) {   var arr = new array(length || 0),       = 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 argument length of each dimension. usage examples:

  • var multiarray = createarray(10,10,10); gives 3-dimensional array of equal length.
  • var weirdarray = createarray(34,6,42,2); gives 4-dimensional array of unequal lengths.

Comments

Popular posts from this blog

html5 - What is breaking my page when printing? -

c# - must be a non-abstract type with a public parameterless constructor in redis -

ajax - PHP/JSON Login script (Twitter style) not setting sessions -