Domanda

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?

È stato utile?

Soluzione 4

If you take a closer look at this for in loop:

var obj = {
  a: "property 1", 
  b: "property 2", 
  c: "property 3", 
  d: "property 4"
}
for (var prop in obj) {
    if (typeof(prop) == 'string') {
        console.log('This is a string!');
    }
}

You will notice that the what the for in loop is giving you is the name of the property. That's why it would be ok to use obj[prop] because the property would be a string and that is a legal way to access a property of an object.

When you try and execute obj.prop it gives you undefined because property is a string that represents the name of a property, it's not the actual property.

Altri suggerimenti

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.

o[p]

is p-th element in array o.

o.p

is property p of array o, which is correctly reported as undefined, as it doesn't exist.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top