开发者

What does each mean in JavaScript?

开发者 https://www.devze.com 2023-02-28 18:43 出处:网络
myObj.FirstName = \'Phillip\', myObj.LastName = \'Senn\'; for (var X in myObj) // FirstName LastName for each (var X in myObj) // Phillip Senn
myObj.FirstName = 'Phillip',
myObj.LastName = 'Senn';
for (var X in myObj) // FirstName LastName
for each (var X in myObj) // Phillip Senn

Q: M开发者_高级运维entally, how do you read these two statements?


The first one (for ( in )) is reading property names from the object.

So you may read it as for each property in myObj, assign it to x.

The second one (for each ( in )) is reading values of the properties in the object.

This one may be read as for each property's value in myObj, assign it to x.

Note that for each has limited browser support.

Also note that if extra properties are appearing in for ( in ), it is because it will look up the prototype chain for extra enumerable properties (and someone may have augmented Object, for example).

You can mitigate this with...

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

jsFiddle.


for (var a in b) is a way for getting the indices a of the given array b. When I'm muttering to myself as I read through code, I usually say something like "for every X in myObj".

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


for(var X in myObj)

For every member (key) in myObj

for each(var X in myObj)

For each member in myObj, get its value


for iterates through the Names of the properties of the object whereas for each iterates through the values of the properties.

See for each on MDN

0

精彩评论

暂无评论...
验证码 换一张
取 消