Array排序
protected function applicationCompleteHandler(event:FlexEvent):void
{
var array:Array = [];
array.push(new Vga("a",10));
array.push(new Vga("c",2));
array.push(new Vga("f",1.3));
array.push(new Vga("d",1.1));
array.push(new Vga("e",16));
array.push(new Vga("b",0));
trace(array.toString());
//output: [a,10],[c,2],[f,1.3],[d,1.1],[e,16],[b,0]
var defaultSort:Array = array.sort();//默認(rèn)排序
trace(defaultSort.toString());
//output: [a,10],[b,0],[c,2],[d,1.1],[e,16],[f,1.3]
var sortFunArray:Array = array.sort(sortFun);//使用自定義方法排序
trace(sortFunArray.toString());
//output: [b,0],[d,1.1],[f,1.3],[c,2],[a,10],[e,16]
}
/**自定義排序方法*/
public function sortFun(a:Vga,b:Vga):int{
if(a.price < b.price){
return -1; //a在前,b在后
}else if(a.price == b.price){
return 0; //ab位置不變
}else{
return 1; //b在前,a在后
}
}
/**排序VO對(duì)象*/
public class Vga
{
public var name:String;
public var price:Number;
public function Vga(name:String,price:Number)
{
this.name = name;
this.price = price;
}
public function toString():String{
return "["+this.name+","+this.price+"]";
}
}
ArrayCollection排序
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute">
<mx:Script>
<![CDATA[
import mx.collections.SortField;
import mx.collections.Sort;
import mx.collections.ArrayCollection;
private var acSort:ArrayCollection=
new ArrayCollection([{id:0,userName:"zhangSan",age:21},
{id:2,userName:"liSi",age:24},
{id:1,userName:"wangWu",age:31}]);
private function sortAc():ArrayCollection{
var sort:Sort=new Sort();
//按照ID升序排序
sort.fields=[new SortField("id")];
//按照userName降序排序
sort.fields=[new SortField("userName",true,true)];
//先按ID升序,再按userName降序
sort.fields[new SortField("id"),new SortField("userName",true,true)];
acSort.sort=sort;
acSort.refresh();//更新
return acSort;
}
/*
其實(shí)看看API就一目了然
SortField () 構(gòu)造函數(shù)
public function SortField(name:String = null,
caseInsensitive:Boolean = false,
descending:Boolean = false,
numeric:Object = null)
參數(shù)
name:String (default = null) — 此字段用來(lái)進(jìn)行比較的屬性的名稱。如果該對(duì)象為簡(jiǎn)單類型,則傳遞 null。
caseInsensitive:Boolean (default = false) — 在對(duì)字符串進(jìn)行排序時(shí),指示比較運(yùn)算符是否忽略值的大小寫。
descending:Boolean (default = false) — 指示比較運(yùn)算符是否按降序排列項(xiàng)目。
numeric:Object (default = null) — 指示比較運(yùn)算符是否按編號(hào)而不按字母順序比較排序項(xiàng)目。
*/
]]>
</mx:Script>
</mx:Application>
posted on 2013-03-17 12:19
wkkyo 閱讀(4425)
評(píng)論(0) 編輯 收藏 所屬分類:
Flex