Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
757 views
in Technique[技术] by (71.8m points)

loops - What is the difference between for..in and for each..in in javascript?

What is the difference between for..in and for each..in statements in javascript? Are there subtle difference that I don't know of or is it the same and every browser has a different name for it?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

"for each...in" iterates a specified variable over all values of the specified object's properties.

Example:

var sum = 0;
var obj = {prop1: 5, prop2: 13, prop3: 8};
for each (var item in obj) {
  sum += item;
}
print(sum); // prints "26", which is 5+13+8

Source

"for...in" iterates a specified variable over all properties of an object, in arbitrary order.

Example:

function show_props(obj, objName) {
   var result = "";
   for (var i in obj) {
      result += objName + "." + i + " = " + obj[i] + "
";
   }
   return result;
}

Source


Note 03.2013, for each... in loops are deprecated. The 'new' syntax recommended by MDN is for... of.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...