What does everyone mean in javascript?

myObj.FirstName = 'Phillip', myObj.LastName = 'Senn'; for (var X in myObj) // FirstName LastName for each (var X in myObj) // Phillip Senn 

Q: Mentally, how do you read these two statements?

+6
source share
4 answers

The first ( for ( in ) ) reads the property names from the object.

So you can read it as for every property in myObj , assign it x .

The second ( for each ( in ) ) reads the property values โ€‹โ€‹of the object.

This can be read as for each property value in myObj , assign it x .

Please note that for each has limited browser support.

Also note that if additional properties appear in for ( in ) , this is due to the fact that he will look for a prototype chain for additional enumerated properties (for example, someone may have Object added).

You can reduce this with ...

 for (var x in myObj) { if ( ! myObj.hasOwnProperty(x)) { continue; } // Now you are sure the property is of `myObj` } 

jsFiddle .

+7
source

for (var a in b) - a way to get the indices a given array b . When I mutter to myself, when I read the code, I usually say something like "for every X in myObj ."

If you use the each keyword, you will get the values โ€‹โ€‹of the object (or array) in myObj . If you omit it, myObj will contain the keys (or array indices).

+1
source

for(var X in myObj)

For each member (key) in myObj

for each(var X in myObj)

For each member in myObj get its value

+1
source

for iterates through the property names of the object, while for each iterates through the property values.

See for everyone in MDN

+1
source

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


All Articles