ArrayCollection操作范例
<?xml version="1.0" encoding="utf-8"?>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/halo" minWidth="1024" minHeight="768">
<fx:Script>
<![CDATA[
import mx.collections.ArrayCollection;
//添加对象
public function insertCollection():void{
//方法1
//一个花括号代表一个对象
var selectType01:String = "东京";
var selectType02:String = "横滨";
var oneArrayCollection:ArrayCollection = new
ArrayCollection([{label:selectType01, data:1}, {label:selectType02,
data:2}]);
//方法2
var twoArrayCollection:ArrayCollection;
var array:Array = new Array();
for(var i:Number = 0; i < 10; i++){
array.unshift({city:"B" + i, data:i, size:1000 + i});
}
twoArrayCollection = new ArrayCollection(array); //长度为10,也就是有10个对象
//方法3
var threeArrayCollection:ArrayCollection = new ArrayCollection();
for(var j:Number = 0; j < 5; j++){ //添加5个对象
threeArrayCollection.addItem({name:"C" + j, sequence:j, ok:"hello" + j});
}
trace(threeArrayCollection[2].ok); //hello2
//方法4,在指定的索引处添加对象
threeArrayCollection.addItemAt({name:"K", sequence:"A", ok:"H"},2);
trace(threeArrayCollection[2].ok); //H
//方法5,在制定的索引处添加对象
threeArrayCollection.setItemAt({name:"W", sequence:"X", ok:"Q"}, 5);
trace(threeArrayCollection[5].sequence); //X
}
//删除对象,ArrayCollection相当于数组(数组集合)
public function deleteCollection():void{
var delCollection:ArrayCollection = new ArrayCollection();
for(var j:Number = 0; j < 5; j++){ //添加5个对象
delCollection.addItem({name:"DEL" + j, sequence:j, ok:"hello" + j});
}
for(var value:String in delCollection){
trace(delCollection[value].ok);
}
delCollection.removeItemAt(2); //删除第三个元素
for(var value2:String in delCollection){
trace(delCollection[value2].ok);
}
delCollection.removeAll(); //全部删除
for(var value3:String in delCollection){
trace("=========");
trace(delCollection[value3].ok);
}
}
//查询对象
public function selectCollection():void{
var twoArrayCollection:ArrayCollection;
var array:Array = new Array();
for(var i:Number = 0; i < 10; i++){
array.unshift({city:"B" + i, data:i, size:1000 + i});
}
twoArrayCollection = new ArrayCollection(array); //ArrayCollection的构造方法有参数的话则一定是Array对象作为参数
if(twoArrayCollection.contains(array[1])){
var objIndex:int = twoArrayCollection.getItemIndex(array[1]); //返回该项目的索引
trace(objIndex);
}
// trace("OK");
// }
}
]]>
</fx:Script>
<mx:Button id="insertID" x="320" label="添加对象" click="insertCollection();"/>
<mx:Button id="deleteID" x="450" label="删除对象" click="deleteCollection();"/>
<mx:Button id="seleteID" x="600" label="查询对象" click="selectCollection();"/>
<fx:Declarations>
<!-- Place non-visual elements (e.g., services, value objects) here -->
</fx:Declarations>
</s:Application>