Javascript for ... in a loop, please explain

My first question is here and need help understanding the for in loop in JavaScript.

When I run the following code, I get "undefined" from the warning function:

var o = { a: "property 1", b: "property 2", c: "property 3", d: "property 4" } for (p in o) { alert(op); } 

but if I had to change . to [ ] (ie alert(o[p]) ), the warning will return the value of the property as expected.

Why can not I use . to access the property of an object?

+4
source share
4 answers

If you take a closer look at this in a 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 what the for in loop gives you is the name of the property. Therefore, it would be convenient to use obj[prop] , because the property will be a string, and this is a legitimate way to access the object of the object.

When trying to execute obj.prop it gives you undefined because the property is a string that represents the name of the property, not the actual property.

+1
source

Imagine you have this object:

 var o = { a: "property 1", b: "property 2", c: "property 3", d: "property 4", p: "property 5" } 

and do the following:

 for (p in o) { console.log(op); } 

the result will be:

 property 5 property 5 property 5 property 5 property 5 

Because op means you want to get the value of a property named p .

Similarly, in your example, the p property is not defined in your object.

If you want to get the value of a property using a string , you must use the notation [] .

+3
source
 o[p] 

is the pth element in the array o.

 op 

is the p property of the array o, which is correctly specified as undefined since it does not exist.

+2
source

op means the property "p" of o .

o ["p"] means the same thing.

o [x] means some property (whose value is determined by the variable x ) o .

o [p] is the same.

+2
source

Source: https://habr.com/ru/post/1499463/


All Articles