Reputation: 1902
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?
Upvotes: 2
Views: 6388
Reputation: 3404
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);
}
Upvotes: 0
Reputation: 26878
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 */
}
Upvotes: 8
Reputation:
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")
}
}
Upvotes: 2