简体   繁体   English

循环遍历javascript对象IE8

[英]Loop over javascript object IE8

data is an array of Json data The structure of each object is: 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"
    }
}
];

When I try to access the array in a loop (only happens in IE8, IE7) with: 当我尝试在循环中访问数组时(仅在IE8,IE7中发生):

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

I got an error message: "Impossible to get property of "height" the reference is null or not defined" 我收到一条错误消息:“无法获取”height“属性,引用为null或未定义”

(I translated the message from french: Impossible d'obtenir la propriété « height » d'une référence null ou non définie) (我翻译了法语的消息:Impossible d'obtenirlapropriété«height»d'uneréférencenullounondéfinie)

What am I doing wrong? 我究竟做错了什么?

Accessing array elements can be done more semantically like this: 访问数组元素可以在语义上更加完成,如下所示:

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

for..in loops are meant to be used with key-based objects. for..in循环意味着与基于键的对象一起使用。

NOTE: you also have a missing closing quote in your object: 注意:您的对象中也有一个缺少的结束引号:

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

It seems you're looking for the property somewhere it doesn't exist 看来你正在寻找一个它不存在的地方

Make a simple test: 做一个简单的测试:

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

There is an array of objects. 有一系列对象。

So, use for and get the required object's property. 因此,使用并获取所需对象的属性。

There is a syntax error in the given code. 给定代码中存在语法错误。 Close the string with quotes. 用引号关闭字符串。

Example code is here. 示例代码在这里。

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM