gpt4 book ai didi

javascript - 遍历javascript对象IE8

转载 作者:行者123 更新时间:2023-12-04 17:57:18 24 4
gpt4 key购买 nike

data 是一个Json数据数组每个对象的结构是:

var data = [
{
id: 0,
img: "image_src",
width: 107,
height: 80,
shadowBoxLink: "....",
th: {
width: 107,
height: 70,
img: "src"
}
},
{
id: 1,
img: "image_src",
width: 107,
height: 80,
shadowBoxLink: "....",
th: {
width: 107,
height: 80,
img: "src"
}
}
];

当我尝试在循环中访问数组时(仅在 IE8、IE7 中发生):

for(var i in data) {
var imgHeight = data[i].th.height;
}

我收到一条错误消息:“无法获取“高度”的属性,引用为空或未定义”

(我从法语翻译了消息:Impossible d’obtenir la propriété « height » d’une référence null ou non définie)

我做错了什么?

最佳答案

访问数组元素可以像这样更语义化地完成:

for(var i = 0, n = data.length; i < n; i ++) {
var imgHeight = data[i].th.height;
...
}

for..in循环旨在与基于键的对象一起使用。

注意:您的对象中还缺少结束引号:

th: Object {
width: 107,
height: 80,
img: "src /* NEED A CLOSING " HERE */
}

关于javascript - 遍历javascript对象IE8,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15522237/

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