增强了2D数组中的循环 - JavaScript

Car*_*los 5 javascript foreach multidimensional-array

我在Javascript中创建了以下2D数组

// Create basic linear array
var ImgArray = new Array(4);

// Do the 2D array for each or the linear array slots
for (i=0; i < 4 ; i++) {
    ImgArray[i] = new Array(4)
}
Run Code Online (Sandbox Code Playgroud)

现在我想用2'增强的for循环'来迭代它.但我坚持如何使用循环,因为只有ImgArray这样说.例如;

// Load the images
for(var i in ImgArray) { 
    for( ??? ) {           // How would i do this? What do i state as an array?
          ///...
    }
    document.write("<br>");
}
Run Code Online (Sandbox Code Playgroud)

任何建议都很赞赏

T.J*_*der 16

假设您创建的数组,循环如下所示:

var i, j, entry, ImgArray;

// Create the array
ImgArray = new Array(4);
for (i=0; i < 4 ; i++) {
    ImgArray[i] = new Array(4);
}

// Loop through both dimensions
for (i = 0; i < ImgArray.length; ++i) {
    entry = ImgArray[i];
    for (j = 0; j < entry.length; ++j) {
        // Do something with entry[j]
    }
}
Run Code Online (Sandbox Code Playgroud)

这是因为JavaScript中没有二维数组.(事实上​​,即使数组也不是真正的数组,但是我们不去那里.)有"数组",数组条目可以是另一个数组,但是一个数组条目可能比其他数组更长或更短.因此,您检索该数组并循环遍历长度,这可能与同一"维度"中的其他数据不同.

请注意,我没有for..in在上面使用.除非你真的知道你在做什么,否则不要使用for..in循环数组; 这里详细介绍.(如果你真的知道自己在做什么,并采取适当的预防措施,这很好,但你的引用代码没有采取必要的防范措施.)for..in没有遍历数组的索引,它列举了一个对象的属性名称.

偏离主题#1:在JavaScript中,约定(您可以自由忽略)是仅对ImgArray构造函数使用初始大写().

偏离主题#2:您可能会考虑使用数组文字([entry, entry, entry])而不是new Array(...),但这取决于您正在做什么.

偏离主题#3:依赖分号插入是一个非常糟糕的主意(就像你的ImgArray[i] = new Array(4)线一样).确保在需要的地方加上分号,或者你会发现你不能正确地缩小你的脚本和/或你会打击浪费时间的奇怪错误.:-)

  • +1,也是主题#1:不要使用`for ... in`迭代数组.(你的代码说的是,但我想我只是用文字添加它) (3认同)