ForEach < Array

The ForEach function accepts a function as its only parameter. For each element in the array, the function is called with the current element being passed as the first parameter. The function can accept a second parameter of type IterationEventArgs. The loop can be broken by either setting the CancelEvent property of the IterationEventArgs to true or returning false. Below is an example:

var array = ["orange", "berry", "grape"];
array.ForEach(function(i){
    Page.AddElement(i);
});

 

This will write each word to the page as a text element.

 

ForEachReversed and controlling the loop

ForEachReversed operates just as it sounds, it loops through each element in reversed order.

 

You can control how the loop executes by modifying the second parameter passed of type IterationEventArgs. Setting CancelEvent to true or return false from the function will break the execution and stop loop. There is a Navigate property that can be used to skip or back track in an array. On each loop, Navigate is set to 0, but if you set it to a positive number, it will skip that many number of elements for the next call. If the Navigate number causes the index to exceed the number of elements in the array, the loop will stop. If the Navigate is set to a negative number, the loop will backtrack.

 

Object safety

The ForEach loops operate on a copy of the looping object (Array, Dictionary, ObservableArray, etc) so modifying the array during a loop will not affect the loop at all. It will continue to go through the elements that were found in the array on the initial call.

 

Dictionary.ForEach

The Dictionary object contains a ForEach and ForEachReverse function as well. These functions also accept a function to call for each element. The main difference is that “this” refers to a KeyValuePair object that contains the current key and value of the dictionary. All other concepts apply the same as the Array’s ForEach

Last edited May 29, 2011 at 9:59 PM by dahrkdaiz, version 3

Comments

No comments yet.