foreach

Summary

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

Syntax

foreach (variable in object)
    statement;

Parameters

variable
The variable to assign to on each iteration. A variable declaration or valid identifier expression is expected. If variables are declared here, they are scoped to the loop.
object
The object to iterate over.
statement
The statement to execute. In order to execute a group of statements, use a block.

Description

The foreach loop iterates over each element of a collection (such as an array or dictionary). In order to loop over keys of a collection, use the for-in Loop.

The type of the variable in the foreach loop must be a type compatible with the object being iterated over. For example, when looping over an int[] array, the variable assigned to the element for each iteration must be int.

If the object to iterate over has an external type, behavior will vary depending on the runtime type of the object. If the runtime type of the object is a JavaScript array, the foreach loop will iterate over only the array elements. Otherwise, the foreach loop will iterate over each property of the object (including properties inherited through the prototype chain) and assign the value of the property to the foreach loop variable. However, if the JavaScript object has the internal [[DontEnum]] flag set, the property will not be enumerated with either for-in or foreach loops.

If the object to iterate over has an external type, the values iterated over will include values inherited from the prototype chain and the iteration will occur in no guaranteed order. For arrays (both JavaScript and JS++ arrays), the order is guaranteed to be sequential and only the array element values will be enumerated when using foreach. For non-array JS++ containers (such as dictionaries), the order is dependent on the type and may not necessarily be guaranteed.

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 Elements
1
2
3
4
5
6
7
8
9
10
11
12
import System;
 
int[] arr = [ 3, 4, 5 ];
 
foreach (int x in arr) {
    Console.log(x);
}
 
// Output:
// 3
// 4
// 5
Looping Over Dictionary Elements
1
2
3
4
5
6
7
8
9
10
11
12
13
14
import System;
 
Dictionary<int> dict = {{
    "foo": 10,
    "bar": 100
}};
 
foreach (int value in dict) {
    Console.log(value);
}
 
// Output:
// 10
// 100

See Also

Share

HTML | BBCode | Direct Link