问题
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?
回答1:
"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] + "\n";
}
return result;
}
Source
Note 03.2013, for each... in
loops are deprecated. The 'new' syntax recommended by MDN is for... of.
回答2:
This demonstration should hopefully illustrate the difference.
var myObj = {
a : 'A',
b : 'B',
c : 'C'
};
for each (x in myObj) {
alert(x); // "A", "B", "C"
}
for (x in myObj) {
alert(x); // "a", "b", "c"
alert(myObj[x]); // "A", "B", "C"
}
回答3:
Read the excellent MDC documentation.
The first is for normal looping over collections and arbitrarily over an object's properties.
A for...in loop does not iterate over built-in properties. These include all built-in methods of objects, such as String's indexOf method or Object's toString method. However, the loop will iterate over all user-defined properties (including any which overwrite built-in properties).
A for...in loop iterates over the properties of an object in an arbitrary order. If a property is modified in one iteration and then visited at a later time, the value exposed by the loop will be its value at that later time. A property which is deleted before it has been visited will not then be visited later. Properties added to the object over which iteration is occurring may either be visited or omitted from iteration. In general it is best not to add, modify, or remove properties from the object during iteration, other than the property currently being visited; there is no guarantee whether or not an added property will be visited, whether a modified property will be visited before or after it is modified, or whether a deleted property will be visited before it is deleted.
The latter allows you to loop over an object's properties.
Iterates a specified variable over all values of object's properties. For each distinct property, a specified statement is executed.
回答4:
In addition to the other answers, keep in mind that for each...in
is not part of the ECMA standard and also isn't included in the upcoming edition 3.1. It was introduced in JavaScript 1.6, which is an extension of ECMAScript3 by the Mozilla Foundation.
According to the linked Wikipedia page, it's only implemented in Firefox 1.5+ and Safari 3.x(+?).
来源:https://stackoverflow.com/questions/634654/what-is-the-difference-between-for-in-and-for-each-in-in-javascript