for...in

Summary

Iterates over an object's own enumerable properties including the properties inherited from its prototype. Statements can be executed for each enumerable property.

Syntax

for (variable in object)
    statement;

Parameters

variable
The variable to assign a property name on each iteration.
object
The object to iterate over.
statement
The statement to execute. In order to execute a group of statements, use a block.

Description

The for-in loop will loop through all enumerable properties of an object. If the object to iterate over has an external type, the properties iterated over will include properties inherited from the prototype chain and the iteration will occur in no guaranteed order. For JS++ arrays, the order is guaranteed to be sequential and only the array element keys will be enumerated. For non-array JS++ containers (such as dictionaries), the order is dependent on the type and may not necessarily be guaranteed.

Note that when dealing with external types, only the enumerable properties of an object will be iterated over. If an object's property has the internal [[DontEnum]] flag set, the property will not be enumerated with for-in. An example of a property with the internal [[DontEnum]] flag set is JavaScript's Object.prototype.toString. "toString" will not be returned in a for-in loop over an arbitrary object even though the object will inherit "toString" from Object.prototype.

Runtime Modification of Containers

If arrays are modified at runtime, the behavior is defined. Arrays are iterated from the first element to the last element - including modifications.

If dictionary keys are deleted at runtime, the behavior is defined. Deleted dictionary keys that have not yet been visited will not be visited. However, if keys are added at runtime, the behavior is undefined and added keys are not guaranteed to be visited across all web browsers.

Examples

Looping Over Array Keys
1
2
3
4
5
6
7
8
9
10
11
12
import System;
 
int[] arr = [ 50, 40, 30 ];
 
for(int index in arr) {
    Console.log(index);
}
 
// Output:
// 0
// 1
// 2
Looping Over Array Values
1
2
3
4
5
6
7
8
9
10
11
12
import System;
 
int[] arr = [ 50, 40, 30 ];
 
for(int index in arr) {
    Console.log(arr[index]);
}
 
// Output:
// 50
// 40
// 30
Looping Over Dictionary Keys
1
2
3
4
5
6
7
8
9
10
11
12
13
14
import System;
 
Dictionary<int> dict = {{
    "foo": 10,
    "bar": 100
}};
 
for(string key in dict) {
    Console.log(key);
}
 
// Output:
// "foo"
// "bar"
Looping Over Dictionary Values
1
2
3
4
5
6
7
8
9
10
11
12
13
14
import System;
 
Dictionary<int> dict = {{
    "foo": 10,
    "bar": 100
}};
 
for(string key in dict) {
    Console.log(dict[key]);
}
 
// Output:
// 10
// 100

See Also

Share

HTML | BBCode | Direct Link