Export (0) Print
Expand All

for...in Statement (JavaScript)

Executes one or more statements for each property of an object, or each element of an array.

for (variable in [object | array])
   statements 

variable

Required. A variable that can be any property name of object or any element index of an array.

object, array

Optional. An object or array over which to iterate.

statements

Optional. One or more statements to be executed for each property of object or each element of array. Can be a compound statement.

Before each iteration of a loop, variable is assigned the next property name of object or the next element index of array. You can then use it in any of the statements inside the loop to reference the property of object or the element of array.

When iterating over an object, you cannot determine or control the order in which the members of the object are assigned to variable. Moreover, the order may be different in different versions of the language.

Iterating through an array is performed in element order, that is, 0, 1, 2, ...

The following example illustrates the use of the for...in statement with an object used as an associative array.

// Initialize object.
a = {"a" : "Athens" , "b" : "Belgrade", "c" : "Cairo"}

// Iterate over the properties.
var s = ""
for (var key in a) {
    s += key + ": " + a[key];
    s += "<br />";
    }
document.write (s);

// Output:
// a: Athens
// b: Belgrade
// c: Cairo

This example illustrates the use of the for ... in statement to iterate though a JavaScript Array object that has expando properties.

// Initialize the array.
var arr = new Array("zero","one","two");

// Add a few expando properties to the array.
arr["orange"] = "fruit";
arr["carrot"] = "vegetable";

// Iterate over the properties and elements.
var s = "";
for (var key in arr) {
    s += key + ": " + arr[key];
    s += "<br />";
}

document.write (s);

// Output:
//   0: zero
//   1: one
//   2: two
//   orange: fruit
//   carrot: vegetable
NoteNote

Use the Enumerator object to iterate members of a collection.

Supported in the following document modes: Quirks, Internet Explorer 6 standards, Internet Explorer 7 standards, Internet Explorer 8 standards, Internet Explorer 9 standards. See Version Information.

Community Additions

Show:
© 2014 Microsoft