javascript中for..in和each..in语句有什么区别? 是否存在我不知道的细微差别,或者它是否相同,每个浏览器都有不同的名称?

有帮助吗?

解决方案

"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.

其他提示

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"
}

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.

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(+?).

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top