Why can't you access the object property with dot notation inside a loop?
var rockSpearguns = {
Sharpshooter: {barbs: 2, weight: 10, heft: "overhand"},
Pokepistol: {barbs: 4, weight: 8, heft: "shoulder"}
};
function listGuns(guns) {
for ( var gun in guns ) {
console.log("Behold! " + gun + ", with " + gun.heft + " heft!");
}
}
listGuns(rockSpearguns);
This produces this output:
Behold! Sharpshooter, with undefined heft!
Behold! Pokepistol, with undefined heft!
But, if I change gun.heft
to guns[gun].heft
, I get the correct output.
Behold! Sharpshooter, with overhand heft!
Behold! Pokepistol, with shoulder heft!
It seems that I can get the name of the gun inside the loop, but I can't call a method on it to get the heft. Why?
In, say Ruby, inside a loop, the the current item at index is usually an object. No so here?