微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Flex的Array和ArrayCollection总结

Flex的Array和ArrayCollection

1.array作为控件使用    FLEX3写法:       <mx:Array id="barname">           <mx:String>Flash</mx:String>           <mx:String>Director</mx:String>           <mx:String>Dreamweaver</mx:String>           <mx:String>ColdFusion</mx:String>       </mx:Array>    FLEX4写法:       <fx:Array id="barname">           <fx:String>Flex</fx:String>           <fx:String>Flash</fx:String>           <fx:String>Dreamweaver</fx:String>       </fx:Array>    举例    <mx:LinkBar  id="navigationBar" dataProvider="{barname}"/>    <mx:LinkBar  id="navigationBar" dataProvider="barname"/>    注:写{},则当barname数据的值修改后,linkbar的数据同步更新 2.array在程序中使用    [Bindable]    public var barname:Array=["Flex","Flash","Dreamweaver"];    <mx:LinkBar  id="navigationBar" dataProvider="{barname}"/>    var barname:Array = new Array();    barname.push("Flex");    barname.push("Flash");    barname.push("Dreamweaver");    navigationBar.dataProvider = barname; 3.array的排序    private var temp:Array = new Array(1,4,3,45,6,7,77,9);     function sortArray(numbers:Array):Array{              numbers.sort(Array.NUMERIC);        return numbers;     } 4.ArrayCollection特点    ArrayCollection是flex中的数组集合类,它是很常用的,我们使用它时需要注意几个地方 (1)事件监听     ArrayCollection可以为它注册一个集合改变的监听事件(CollectionEvent.COLLECTION_CHANGE),就是一旦 ArrayCollection数组改变就会触发Event,不是所有情况的改变都会触发改变事件,如果集合当中的对象属性没有被绑定,那么你改变它的对象值也是不会触发事件的,在这种情况下你也许可能需要去将对象的属性进行绑定或者通过itemUpdated方法去管理对象值改变,除非集合的长度改变了,事件才会被触发 (2)对象删除     ArrayCollection的对象删除方法removeAll(),有这样一种情况,当你在过滤集合数据的时候,它并不会删除所有数据,而是删除全部过滤的数据,不符合过滤条件的数据就没被删除,依然还在source中 (3)过滤函数     ArrayCollection有个filterFunction过滤函数,就是可能集合中你只需要显示其中某几个对象,你将会需要根据对象条件筛选对象,那么你可能会用过滤函数,过滤函数会将不符合条件的对象过滤出来,但是ArrayCollection有个source属性是不会变的,它是个数组,所有源数据全在里面,尽管你去过滤,所有对象都会一直存在其中 (4)排序     ArrayCollection还有一个sort属性是用来排序的,你可以为其指定排序字段 5.ArrayCollection在程序中使用 (1)插入或删除    import mx.collections.ArrayCollection;     private var coll:ArrayCollection;      coll = new ArrayCollection(             [{name:"Martin Foo",age:25},              {name:"Joe Bar",age:15},              {name:"John Baz",age:23}]);      }    要插入元素,可使用addItemAt和addItem:     coll.addItemAt({name:"James Fez",age:40},0);    coll.addItem({name:"James Fez",age:40}); (2)搜索    Sort 对象提供findItem 方法用于搜索这个ArrayCollection 中的所有元素。 方法原型如下:    public function findItem(items:Array,values:Object,mode:String, returnInsertionIndex:Boolean = false,compareFunction:Function = null):int    Value 参数可以是包含属性和所需值的任何对象。    Mode 字符串可以是Sort.ANY_INDEX_MODE,表示返回任何匹配项索引,Sort.FirsT_INDEX_MODE 表示返回第一个匹配项索引,Sort.LAST_INDEX_MODE 表示返回最后一个匹配项索引。    returnInsertionIndex 参数表示如果该方法找不到由values 参数标识的项目,并且此参数为 true,则findItem() 方法将返回这些值的插入点,也就是排序顺序中应插入此项目的。    compareFunction 设置用于查找该项目的比较运算符函数. 举例    private function checkExistence():int {         var sort:Sort = new Sort();        return sort.findItem(coll.source,{name:nameTI.text,age:Number(ageTI.text)},  Sort.ANY_INDEX_MODE);     } (3)过滤    filterFunction 属性是由ListCollectionView 类定义,它是ArrayCollection 的父类。    当过滤器函数被传递给继承自ListCollectionView 的任何子类后,这里为ArrayCollection 对象,应用过滤器后必须调用refresh 方法    将原型为function(item:Object):Boolean 的函数传递给ArrayCollection 的filter 属性。如果返回true 表示值继续留在ArrayCollection,返回false 表示其值被移除。 举例:   private function init():void {        coll = new ArrayCollection([{name:"Martin Foo",{name:"Joe Bar",name:"John Baz",age:23},{name:"Matt Baz",age:21}]);        coll.filterFunction = filterFunc;        coll.refresh();        for(var i:int = 0; i<coll.length; i++) {            trace(coll.getItemAt(i).name);        }     }     private function filterFunc(value:Object):Object {        if(Number(value.age) > 21) {            return true;        }        return false;     } (4)排序    首先要创建一个Sort,传递一个SortField 对象数组给fields 属性。这些SortField 对象包含的字符串正是每个ArrayCollection 元素将要用来排序的属性。如要对每个对象的age 属性进行排序,创建Sort 对象,传递SortField。     设置排序字段为age:     private function getoldest():void {         var sort:Sort = new Sort();         sort.fields = [new SortField("age")];         coll.sort = sort;         coll.refresh();         trace(coll.getItemAt(0).age+" "+coll.getItemAt(0).name);      }      先按name升序排序,再按age降序排序     sort.fields = [new SortField("name"),new SortField("age",true,true)];  API说明: public function SortField(           name:String = null,            caseInsensitive:Boolean = false,            descending:Boolean = false,            numeric:Object = null) 参数       name:String (default = null) — 此字段用来进行比较的属性名称。如果该对象为简单类型,则传递 null。      caseInsensitive:Boolean (default = false) — 在对字符串进行排序时,指示比较运算符是否忽略值的大小写。     descending:Boolean (default = false) — 指示比较运算符是否按降序排列项目。       numeric:Object (default = null) — 指示比较运算符是否按编号而不按字母顺序比较排序项目。  6.Array和ArrayCollection的比较 Array的优点:    1)Array的性能优于ArrayCollection,从测试结果平均看来,ArrayCollection的效率是随着object的数目呈线性下降的,而Array则是体现了优异的效率,在object增加的情况下,基本上没有太大的变化。所以如果在你需要遍历所有元素的情况下(比如说物理引擎,3D引擎等),Array是不错的选择      程序见附件1.    2)后台JavaBean也用的是数组[]    3)for循环数组似乎比for each  ArrayConllection看起来更“傻瓜化”    4)给Array数组扩展长度,也可以变通实现,而且代价并不大 ArrayCollection的优点:    1)ArrayCollection 实现接口 ICollectionView,在 Flex 的类定义内属于[数据集],他提供更强大的检索、过滤、排序、分类、更新监控等功能。类似的类还有 XMLListCollection    2)用 array 在作为 dataProvider 绑定于 control 之上,就无法获得控件的更新(实际上效果是可以得到更新的),除非控件被重新绘制或者 data provider 被重新指定,而 Collection 则是将 array 的副本存储于 Collection 类的某个对象之中,其特点是 Collection 类本身就具备了确保数据同步的方法,例子如下(取自 adobe 内部工程师 training 示例,稍有改变)    3)对ArrayCollection中的对象进行增加删除更新操作时ArrayCollection会产生事件,可以通过collectionchange事件监听,所以在图表开发中都用ArrayCollection做数据源,一旦有更新,就会反映在图标上 附件1:    <?xml version="1.0" encoding="utf-8"?> <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" frameRate="100" layout="vertical" horizontalAlign="center">     <mx:Script>         <![CDATA[             import mx.collections.ArrayCollection;             [Bindable]             private var ds:ArrayCollection;             private var array:Array;             private var ac:ArrayCollection;             public function loop(loopCount:uint):Object             {                 array = null;                 ac = null;                 var begin:uint;                 var end:uint;                 var interval1:Number = 0;                 var interval2:Number = 0;                 var interval3:Number = 0;                 var interval4:Number = 0;                 var i:uint;                 // for array,insert to array                 i=0;                 array= new Array();                 begin = getTimer();                 for (i;i<loopCount;i++)                 {                     array.push({test:"helllo"});                 }                 end = getTimer();                 interval1 =  end - begin;                 t1.text = interval1.toString()+" ms";                 //loop the array                 i=0;                 begin = getTimer();                 for (i;i<array.length;i++)                 {                     array[i];                 }                 end = getTimer();                 interval3 =  end - begin;                 t3.text = interval3.toString()+" ms";                 /// for ac,insert to array collection                 i=0;                 ac=  new ArrayCollection();                 begin = getTimer();                 for (i;i<loopCount;i++)                 {                     ac.addItem({test:"helllo"});                 }                 end = getTimer();                 interval2 =  end - begin;                 t2.text = interval2.toString()+ " ms";                 //loop the array collection                 i=0;                 begin = getTimer();                 for (i;i<ac.length;i++)                 {                     ac.getItemAt(i);                 }                 end = getTimer();                 interval4 =  end - begin;                 t4.text = interval4.toString()+ " ms";                 return {ct:loopCount,                 array_insert:interval1,                 ac_insert:interval2,                 array_loop:interval3,                 ac_loop:interval4                 };             }             private function autoLoop():void             {                 ds=null;                 ds = new ArrayCollection();                 var i:uint=0;                 for (i;i<parseInt(count.text);i+=parseInt(count.text)>100?parseInt(count.text)/10:1)                 {                     ds.addItem(loop(i));                 }             }             public function reset():void             {                 t1.text ="0";                 t2.text ="0";                 t3.text = "0";                 t4.text = "0";                 count.text = "1000";                 ds=null;                 ds = new ArrayCollection();             }         ]]>     </mx:Script>     <mx:ApplicationControlBar width="503">         <mx:Label text="插入条数:" fontSize="12" color="#0B333C" fontWeight="bold"/>         <mx:TextInput width="98" text="1000" id="count"/>         <mx:Button id="startBtn0" label="Test" click="autoLoop()"/>         <mx:VRule height="15"/>         <mx:Button label="reset" click="reset()"/>     </mx:ApplicationControlBar>     <mx:Panel width="500" height="480" layout="horizontal" id="testbed" title="Array 与Array Collection的性能比较" fontSize="11" fontWeight="normal">         <mx:Canvas width="100%" height="100%" id="main" borderStyle="none" autoLayout="false"  horizontalScrollPolicy="off" fontSize="10">             <mx:LineChart id="lc" x="8.5" y="133" width="463" height="306"  showdatatips="true" dataProvider="{ds}" >                 <mx:horizontalAxis>                     <mx:CategoryAxis dataProvider="{ds}" categoryField="ct" title="插入Object数目"/>                 </mx:horizontalAxis>                 <mx:verticalAxis>                     <mx:Linearaxis id="la" minimum="-1" title="响应时间(毫秒)"/>                 </mx:verticalAxis>                 <mx:series>                     <mx:Lineseries displayName="array 插入耗时" yField="array_insert" />                     <mx:Lineseries displayName="arraycollection 插入耗时" yField="ac_insert"/>                     <mx:Lineseries displayName="array 遍历耗时" yField="array_loop"/>                     <mx:Lineseries displayName="arraycollection 遍历耗时" yField="ac_loop"/>                 </mx:series>             </mx:LineChart>             <mx:HBox x="10" y="0" width="460" height="134" horizontalAlign="left" verticalAlign="middle">                 <mx:Grid horizontalGap="1"  borderThickness="1" borderColor="#C6C6C6"  borderStyle="solid">                     <mx:GridRow width="100%" height="100%">                         <mx:GridItem width="86" height="100%">                             <mx:Label text="毫秒(ms)" fontSize="12"/>                         </mx:GridItem>                         <mx:GridItem width="100%" height="100%" fontSize="12">                             <mx:Label text="Array"/>                         </mx:GridItem>                         <mx:GridItem width="100%" height="100%" fontSize="12">                             <mx:Label text="ArrayCollection"/>                         </mx:GridItem>                     </mx:GridRow>                     <mx:GridRow width="100%" height="100%">                         <mx:GridItem width="66" height="100%">                             <mx:Label text="插入耗时" fontSize="12"/>                         </mx:GridItem>                         <mx:GridItem width="100%" height="100%">                             <mx:Text text="0" width="80" id="t1" fontSize="12"/>                         </mx:GridItem>                         <mx:GridItem width="100%" height="100%">                             <mx:Text text="0" id="t2" width="80" fontSize="12"/>                         </mx:GridItem>                     </mx:GridRow>                     <mx:GridRow width="100%" height="100%">                         <mx:GridItem width="100%" height="100%">                             <mx:Label text="遍历耗时" fontSize="12"/>                         </mx:GridItem>                         <mx:GridItem width="100%" height="100%" fontSize="12">                             <mx:Text text="0" width="80" id="t3"/>                         </mx:GridItem>                         <mx:GridItem width="100%" height="100%">                             <mx:Text text="0" id="t4" width="80" fontSize="12"/>                         </mx:GridItem>                     </mx:GridRow>                 </mx:Grid>                 <mx:VRule height="73" width="3"/>                 <mx:Legend dataProvider="{lc}" width="100%" direction="vertical" fontSize="9" verticalGap="2" fontWeight="normal" fontStyle="normal" fontFamily="Verdana"/>             </mx:HBox>         </mx:Canvas>     </mx:Panel>     <mx:LinkButton label="beherca" click="navigatetoURL(new URLRequest('http://blog.beherca.com'),'_blank')"/> </mx:Application> 

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐