本文介绍了对于多维javascript数组中的循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
从现在开始,我正在使用这个循环来迭代数组的元素,即使我在其中放置具有各种属性的对象,它也能正常工作。
Since now, I'm using this loop to iterate over the elements of an array, which works fine even if I put objects with various properties inside of it.
var cubes[];
for (i in cubes){
cubes[i].dimension
cubes[i].position_x
ecc..
}
现在,让我们假设cubes []以这种方式声明
Now, let's suppose cubes[] is declared this way
var cubes[][];
我可以在 Javascript 中执行此操作吗?我怎样才能自动迭代
Can I do this in Javascript? How can I then automatically iterate in
cubes[0][0]
cubes[0][1]
cubes[0][2]
cubes[1][0]
cubes[1][1]
cubes[1][2]
cubes[2][0]
ecc...
作为解决方法,我可以声明:
As a workaround, I can just declare:
var cubes[];
var cubes1[];
并与两个数组分开工作。这是一个更好的解决方案吗?
and work separately with the two arrays. Is this a better solution?
推荐答案
你可以这样做:
var cubes = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
];
for(var i = 0; i < cubes.length; i++) {
var cube = cubes[i];
for(var j = 0; j < cube.length; j++) {
display("cube[" + i + "][" + j + "] = " + cube[j]);
}
}
工作jsFiddle:
Working jsFiddle:
- http://jsfiddle.net/TRR4n/
上述输出:
cube[0][0] = 1
cube[0][1] = 2
cube[0][2] = 3
cube[1][0] = 4
cube[1][1] = 5
cube[1][2] = 6
cube[2][0] = 7
cube[2][1] = 8
cube[2][2] = 9
这篇关于对于多维javascript数组中的循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!