I'm having trouble understanding the for/in statement in JavaScript.
The book which I'm using explains it as:
for(variable in object){
statement
}
So take for example:
var links = {
link1: {img: '/img/link1.jpg', w: 100 },
link2: {img: '/img/link2.jpg', w: 140 }
};
How would I print out all the links?
If I use:
for(x in links){
document.write(x);
}
It writes out the 2 property names (link1, link2)
, but I开发者_高级运维'm having trouble understanding how to access those properties nested a level deeper, my first thought was a nested for/in
loop but I just don't understand the syntax. E.g. In the code above, does x
refer to the property name? If so wouldn't x.img
get the img
property? Or is my thinking way off?
I would appreciate any references or links to examples, I just find the 2 code examples from the book don't help me understand as much as I'd like.
x
refers to the property name, but not the property value. So to access the property value, you'd need to do object[x]
.
So, for example:
for (key in links) {
var linkProperties = links[key];
document.write(key + ": \n");
for (property in linkProperties) {
var propertyValue = linkProperties[property];
document.write(" " + property + " = " + propertyValue + "\n");
}
}
would give
link1:
img = /img/link1.jpg
w = 100
link2:
img = /img/link2.jpg
w = 140
Also worth mentioning: as discussed in the answers to this question, a hasOwnProperty
guard clause is almost always desired when using for ... in
.
for(x in links){
document.write(links[x]);
}
精彩评论