我有一个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>
答案 0 :(得分:1)
for...in
循环是麻烦。只需使用传统的for
循环索引数组:
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;
答案 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", ...
});