有没有更简洁的方法来初始化空的多维数组?
我一直试图找到一种相当简洁的方法来设置空的多维JavaScript数组的维度,但到目前为止还没有成功。
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.
首先,我尝试使用 var theArray = new Array(10,10 10)
初始化一个空的10x10x10数组,但相反,它只创建了一个包含3个元素的1维数组。
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.
我已经想出如何使用嵌套的for循环初始化一个空的10x10x10数组,但是用这种方式编写数组初始化器非常繁琐。使用嵌套for循环初始化多维数组可能非常繁琐:是否有更简洁的方法在JavaScript中设置空多维数组的维度(具有任意多个维度)?
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));
改编自这个答案:
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);
给出一个等长的三维数组。 -
var weirdArray = createArray(34,6,42,2);
给出一个不等长的4维数组。
-
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.