Iteration is a pretty strange business in ActionScript . AS is an ad-hoc combination of class-based and object-based object orientation and lacks proper (and uniformly implemented) collections. Here are some common iteration paradigms that are useful for copy-paste programming.
Iterating over an array
var array:Array = ["a", "b", "c"];
for each (var element:String in array)
{
trace(element);
}
NB. using the "for each" construct. Using "for" alone is syntactically correct, but it would iterate over the indices (0,1,2).
Iterating over an object's dynamic properties (dictionary iteration)
1. Iterating over property names
var object:Object = {key1:"value 1", key2: "value 2"};
for (var property:String in object)
{
trace(property + ":" + object[property]);
}
2. Iterating over property values
var object:Object = {key1:"value 1", key2: "value 2"};
for each (var value:String in object)
{
trace(value);
}
Note the difference between the "for" construct used in (1) and "for each" used in (2).
Iterating over ICollectionView (Flex only)
In Flex, built-in collections intended for binding to visual components implement ICollectionView. The only general way to iterate over elements in them is using an IViewCursor.
var ac:ICollectionView= new ArrayCollection(["a", "b", "c"]);
for (var cursor:IViewCursor= ac.createCursor(); !cursor.afterLast; cursor.moveNext())
{
var element:String = cursor.current;
trace(element);
}
Iterating over an array
var array:Array = ["a", "b", "c"];
for each (var element:String in array)
{
trace(element);
}
NB. using the "for each" construct. Using "for" alone is syntactically correct, but it would iterate over the indices (0,1,2).
Iterating over an object's dynamic properties (dictionary iteration)
1. Iterating over property names
var object:Object = {key1:"value 1", key2: "value 2"};
for (var property:String in object)
{
trace(property + ":" + object[property]);
}
2. Iterating over property values
var object:Object = {key1:"value 1", key2: "value 2"};
for each (var value:String in object)
{
trace(value);
}
Note the difference between the "for" construct used in (1) and "for each" used in (2).
Iterating over ICollectionView (Flex only)
In Flex, built-in collections intended for binding to visual components implement ICollectionView. The only general way to iterate over elements in them is using an IViewCursor.
var ac:ICollectionView= new ArrayCollection(["a", "b", "c"]);
for (var cursor:IViewCursor= ac.createCursor(); !cursor.afterLast; cursor.moveNext())
{
var element:String = cursor.current;
trace(element);
}