I have a object that looks like this:
var obj = {
Laser: [0, 2],
Missile: [4, 4]
}
using literal notation, i can access the properties just fine:
for (prop in obj){
console.log(prop + " scored " + obj[prop][0] + " out of " + obj[prop][1] + " shots.");
Why cant the same be said using dot-notation like this ?
for (prop in obj){
console.log(prop + " scored " + obj.prop[0] + " out of " + obj.prop[1] + " shots.");
-> error
thanks in advance
Because these two examples are not the same. The first one is ok:
prop == "Laser"
obj[prop] == obj["Laser"]
obj["Laser"][0] === 0
prop == "Missile"
obj[prop] == obj["Missile"]
obj["Missile"][0] == 4
In the second one you are trying to access "prop"
property, which is undefined:
obj.prop == obj["prop"]
obj["prop"] === undefined
obj["prop"][0] // TypeError: Cannot read property "0" of undefined
And, btw, this has nothing to do with JSON.