Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loop over javascript object IE8

data is an array of Json data The structure of each object is:

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:

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"

(I translated the message from french: Impossible d’obtenir la propriété « height » d’une référence null ou non définie)

What am I doing wrong?

like image 919
Alucard Avatar asked Dec 01 '25 08:12

Alucard


1 Answers

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.

NOTE: you also have a missing closing quote in your object:

th: Object {
   width: 107,
   height: 80, 
   img: "src /* NEED A CLOSING " HERE */
}
like image 51
Chris Avatar answered Dec 02 '25 21:12

Chris