JavaScript的; n维数组创建 [英] JavaScript; n-dimensional array creation
问题描述
在构建一个JavaScript间preTER一个简单语言的过程中,我所面临的问题如下;
In the process of building a JavaScript interpreter for a simple language, I've faced the following problem;
解析后,我们得到的索引的阵列,用于指定在n维阵列的元件进行修改。例如,解析此之后:
After parsing, we get an array of indices that specifies the element in an n-dimensional array to be modified. For instance, after parsing this:
a[1, 1, 1]
我们得到一个数组 [1,1,1]
。我工作的语言没有变量定义,所以变量得到他们的第一次使用初始化。我的目标是能够创造这个n维数组,这样我可以把它放在变量表(在上面的例子中,我们需要创建一个3维数组)。
We get an array [1, 1, 1]
. The language I'm working on doesn't have variable definitions, so variables get initialized on their first use. My goal is to be able to create this n-dimensional array so that I can place it in the variable table (in the example above, we'd need to create a 3-dimensional array).
短的问题:
有没有办法使用JavaScript创建 n维数组,而不是的eval()
?
The short question:
Is there a way to create an n-dimensional array in JavaScript without usingeval()
?
推荐答案
未经测试的:
function createNDimArray(dimensions) {
if (dimensions.length > 0) {
var dim = dimensions[0];
var rest = dimensions.slice(1);
var newArray = new Array();
for (var i = 0; i < dim; i++) {
newArray[i] = createNDimArray(rest);
}
return newArray;
} else {
return undefined;
}
}
然后 createNDimArray([3,2,5])
应该返回一个3x2x5数组。
Then createNDimArray([3, 2, 5])
should return a 3x2x5 array.
您可以使用类似的递归过程来访问一个元素,其索引是一个数组:
You can use a similar recursive procedure to access an element whose index is in an array:
function getElement(array, indices) {
if (indices.length == 0) {
return array;
} else {
return getElement(array[indices[0]], indices.slice(1));
}
}
设置元素是相似的,而作为练习留给读者&NBSP;
Setting an element is similar, and left as an exercise for the reader.
这篇关于JavaScript的; n维数组创建的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!