[英]Loop over javascript object IE8
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;
}
我收到一條錯誤消息:“無法獲取”height“屬性,引用為null或未定義”
(我翻譯了法語的消息:Impossible d'obtenirlapropriété«height»d'uneréférencenullounondé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 */
}
看來你正在尋找一個它不存在的地方
做一個簡單的測試:
for(var i in data) {
if(data[i] && data[i].th && data[i].th.height){
console.log('the property exists');
}else{
console.log("no, it doesn't")
}
}
有一系列對象。
因此,使用並獲取所需對象的屬性。
給定代碼中存在語法錯誤。 用引號關閉字符串。
示例代碼在這里。
var data = [
{
id: 0,
img: "image_src1",
width: 107,
height: 80,
shadowBoxLink: "....",
th: {
width: 107,
height: 70,
img: "src"
}
},
{
id: 1,
img: "image_src2",
width: 107,
height: 80,
shadowBoxLink: "....",
th: {
width: 107,
height: 40,
img: "src"
}
}
];
for(var i=0; i<data.length; i++) {
var imgHeight = data[i].th.height;
alert(imgHeight);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.