Våra volontärer har inte översatt denna artikel till Svenska ännu. Gå med oss och hjälpa till att få jobbet gjort!
Du kan också läsa artikeln på English (US).

The for each...in statement is deprecated as the part of ECMA-357 (E4X) standard. E4X support has been removed. Consider using for...of instead.

Firefox now warns about the usage of for each...in and it no longer works starting with Firefox 57.
Please see Warning: JavaScript 1.6's for-each-in loops are deprecated for migration help.

The for each...in statement iterates a specified variable over all values of object's properties. For each distinct property, a specified statement is executed.

Syntax

for each (variable in object) {
  statement
}
variable
Variable to iterate over property values, optionally declared with the var keyword. This variable is local to the function, not to the loop.
object
Object for which the properties are iterated.
statement
A statement to execute for each property. To execute multiple statements within the loop, use a block statement ({ ... }) to group those statements.

Description

Some built-in properties are not iterated over. These include all built-in methods of objects, e.g. String's indexOf method. However, all user-defined properties are iterated over.

Examples

Using for each...in

Warning: Never use a loop like this on arrays. Only use it on objects. See for...in for more details.

The following snippet iterates over an object's properties, calculating their sum:

var sum = 0;
var obj = {prop1: 5, prop2: 13, prop3: 8};

for each (var item in obj) {
  sum += item;
}

console.log(sum); // logs "26", which is 5+13+8

Specifications

Not part of a current ECMA-262 specification. Implemented in JavaScript 1.6 and deprecated.

Browser compatibility

Update compatibility data on GitHub
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariAndroid webviewChrome for AndroidEdge MobileFirefox for AndroidOpera for AndroidiOS SafariSamsung InternetNode.js
Basic support
DeprecatedNon-standard
Chrome No support NoEdge No support NoFirefox No support 1.5 — 57IE No support NoOpera No support NoSafari No support NoWebView Android No support NoChrome Android No support NoEdge Mobile No support NoFirefox Android No support 4 — 57Opera Android No support NoSafari iOS No support NoSamsung Internet Android No support Nonodejs No support No

Legend

No support  
No support
Non-standard. Expect poor cross-browser support.
Non-standard. Expect poor cross-browser support.
Deprecated. Not for use in new websites.
Deprecated. Not for use in new websites.

See also

  • for...in - a similar statement that iterates over the property names.
  • for...of - a similar statement that iterates over the property values but can only be used for iteratable types, so not for generic objects
  • for

Dokumenttaggar och bidragare

Senast uppdaterad av: fscholz,