My first question on here and need help understanding the for in loop in JavaScript.
When I run the following code I get "undefined" from the alert function:
var o = {
a: "property 1",
b: "property 2",
c: "property 3",
d: "property 4"
}
for (p in o) {
alert(o.p);
}
but if I were to change .
to [ ]
(ie. alert(o[p])
) the alert would return the property value as expected.
Why can't I use .
to access the object property?
Imagine you have this object:
var o = {
a: "property 1",
b: "property 2",
c: "property 3",
d: "property 4",
p: "property 5"
}
and run the following:
for (p in o) {
console.log(o.p);
}
the result will be:
property 5
property 5
property 5
property 5
property 5
Because o.p
means that you want to get the value of a property named p
.
Similarly in your example, the property p
is not defined in your object.
If you want to get the value of a property via a string, you must use []
notation.
o.p means the property "p" of o
.
o["p"] means the same thing.
o[x] means some property (whose value is defined by variable x
) of o
.
o[p] the same.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With