Javascript:不了解关联数组的循环

时间:2017-08-27 08:12:49

标签: javascript json for-in-loop

我有一个JSON对象(这是我认为我已定义的),我正在尝试访问其中的数组值。它循环三次是正确的,但img.iName的值始终为undefined

我误解了什么?

<div id="dbgDIV">Debug Div<br></div>
<script>
    // imgs as a JSON array
    var gallery = {"imgs":
                [ // Height and Width to be added
                    {"iName":"File1.jpg", "tName": "File1_th.jpg","cap":"This is a Caption for File1"},
                    {"iName":"File2.jpg", "tName": "File2_th.jpg","cap":"This is a Caption for File2"},
                    {"iName":"File3.jpg", "tName": "File3_th.jpg","cap":"This is a Caption for File3"}
                ],
                "imgCount":"3"
    };
    var dbgDIV = document.getElementById("dbgDIV");
    for (var img in gallery.imgs) {
        dbgDIV.innerHTML = dbgDIV.innerHTML + "img=" + img.iName + "<br>";
        console.log(img.iName);
    }

</script>

3 个答案:

答案 0 :(得分:1)

for...in循环是麻烦。只需使用传统的for循环索引数组:

&#13;
&#13;
var gallery = {
  "imgs": [
    {
      "iName": "File1.jpg",
      "tName": "File1_th.jpg",
      "cap": "This is a Caption for File1"
    },
    {
      "iName": "File2.jpg",
      "tName": "File2_th.jpg",
      "cap": "This is a Caption for File2"
    },
    {
      "iName": "File3.jpg",
      "tName": "File3_th.jpg",
      "cap": "This is a Caption for File3"
    }
  ],
  "imgCount": "3"
};
var dbgDIV = document.getElementById("dbgDIV");
for (var i = 0; i < gallery.imgs.length; i++) {
  var img = gallery.imgs[i];
  console.log(img.iName);
}
&#13;
&#13;
&#13;

答案 1 :(得分:1)

for ... in循环迭代,所以在数组中它将是

 0,1,2

这些数字没有iName。您可能希望使用for..of循环迭代

for(var img of gallery.imgs)

答案 2 :(得分:1)

你应该使用for ... for / forEach / for循环而不是你使用的for..in循环。

快速演示for..in和for..of循环之间的区别:

Object.prototype.objCustom = function() {}; 
Array.prototype.arrCustom = function() {};

let iterable = [3, 5, 7];
iterable.foo = 'hello';

for (let i in iterable) {
  console.log(i); // logs 0, 1, 2, "foo", "arrCustom", "objCustom"
}
for (let i of iterable) {
  console.log(i); // logs 3, 5, 7
}

这意味着它不会真正通过你想要的数组元素,而是通过对象的所有可枚举属性。 (在javascript中所有变量都是对象)

我建议您选择以下内容:

gallery.imgs.forEach(img => {
  console.log(img.iName) // "File1.jpg" , "File2.jpg", ...
});