The following example shows how you can loop over an Array object and modify items using the Array class’s forEach() method.
Full code after the jump.
<?xml version="1.0" encoding="utf-8"?>
<!-- http://blog.flexexamples.com/2008/04/21/looping-over-each-item-in-an-array-in-actionscript-30/ -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
layout="vertical"
verticalAlign="middle"
backgroundColor="white"
initialize="init();">
<mx:Script>
<![CDATA[
import mx.utils.ObjectUtil;
private function init():void {
beforeTextArea.text = ObjectUtil.toString(dp);
dp.forEach(forEach_test);
dataGrid.dataProvider = dp;
afterTextArea.text = ObjectUtil.toString(dp);
}
private function forEach_test(element:*, index:int, arr:Array):void {
element.lbl = element.name + " (" + element.abbr + ")";
element.idx = index;
}
]]>
</mx:Script>
<mx:Array id="dp">
<mx:Object name="Baltimore Orioles" abbr="BAL" />
<mx:Object name="Boston Red Sox" abbr="BOS" />
<mx:Object name="Chicago White Sox" abbr="CWS" />
<mx:Object name="Cleveland Indians" abbr="CLE" />
<mx:Object name="Detroit Tigers" abbr="DET" />
<mx:Object name="Kansas City Royals" abbr="KC" />
<mx:Object name="Los Angeles Angels of Anaheim" abbr="LAA" />
<mx:Object name="Minnesota Twins" abbr="MIN" />
<mx:Object name="New York Yankees" abbr="NYY" />
<mx:Object name="Oakland Athletics" abbr="OAK" />
<mx:Object name="Seattle Mariners" abbr="SEA" />
<mx:Object name="Tampa Bay Devil Rays" abbr="TB" />
<mx:Object name="Texas Rangers" abbr="TEX" />
<mx:Object name="Toronto Blue Jays" abbr="TOR" />
</mx:Array>
<mx:DataGrid id="dataGrid"
verticalScrollPolicy="on"
width="100%">
<mx:columns>
<mx:DataGridColumn dataField="name" />
<mx:DataGridColumn dataField="abbr" width="80" />
<mx:DataGridColumn dataField="lbl" />
<mx:DataGridColumn dataField="idx" width="40" textAlign="right" />
</mx:columns>
</mx:DataGrid>
<mx:Form width="100%" height="100%">
<mx:FormItem label="Before:" width="100%" height="50%">
<mx:TextArea id="beforeTextArea"
editable="false"
wordWrap="false"
width="100%"
height="100%" />
</mx:FormItem>
<mx:FormItem label="After:" width="100%" height="50%">
<mx:TextArea id="afterTextArea"
editable="false"
wordWrap="false"
width="100%"
height="100%" />
</mx:FormItem>
</mx:Form>
</mx:Application>
View source is enabled in the following example.





0 Responses to “Looping over each item in an Array in ActionScript 3.0”
Leave a Reply