多维javascript数组中的for循环 [英] For loop in multidimensional javascript array

查看:39
本文介绍了多维javascript数组中的for循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从现在开始,我使用这个循环来迭代数组的元素,即使我将具有各种属性的对象放入其中也能正常工作.

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:

上面的输出:

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数组中的for循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆