gpt4 book ai didi

javascript - 二维数组中增强的 for 循环 - JavaScript

转载 作者:数据小太阳 更新时间:2023-10-29 05:41:54 24 4
gpt4 key购买 nike

我在 Javascript 中创建了以下二维数组

// 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)
}

现在我想使用 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>");
}

非常感谢任何建议

最佳答案

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

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]
}
}

这是因为 JavaScript 中没有二维数组。 (事实上​​ ,甚至是 arrays aren't really arrays ,但我们不要去那里。)有“数组”,数组条目可以是另一个数组,但一个数组条目可能比其他数组条目更长或更短。因此,您检索该数组并遍历它的长度,这可能与同一“维度”中的其他数组不同。

请注意,我在上面没有使用 for..in不要使用for..in 来遍历数组,除非你真的知道你在做什么; details here . (如果您确实确实知道自己在做什么并采取了足够的预防措施,那很好,但是您引用的代码没有采取必要的预防措施。)for..in 迭代数组的索引,它枚举对象的属性名称。

题外话 #1:在 JavaScript 中,约定(您可以随意忽略)仅对构造函数使用首字母大写 (ImgArray)。

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

题外话 #3:依赖分号插入是一个非常糟糕的主意(与您的 ImgArray[i] = new Array(4) 行一样)。确保在需要的地方放入分号,否则您会发现无法正确缩小脚本和/或您会遇到浪费时间的奇怪错误。 :-)

关于javascript - 二维数组中增强的 for 循环 - JavaScript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4419537/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com