[AS3]as3数组学习sort用法分析与介绍
sort() 按默认排序,注意:区分大小写,数字也是按字符串来处理
- var arr:Array = ["b","c","a"];
- trace(arr.sort());//得到a,b,c
- arr = ["210","1111","30"];
- trace(arr.sort());//得到1111,210,30
- arr = ["b","X","A","c"];
- trace(arr.sort());//得到A,X,b,c
- arr = ["b","C",235,"a",38,"X",8641];
- trace(arr.sort());//得到235,38,8641,C,X,a,b
sort(args) 按参数排序,一共有5种(注意:除了Array.RETURNINDEXEDARRAY,其它方式只要排序成功,都会实际改变数组)
1. sort(Array.CASEINSENSITIVE) 同sort(),不过不区分大小写,数字也是按字符串来处理
- var arr = ["b","X","A","c"];
- arr.sort(Array.CASEINSENSITIVE);//得到"A","b","c","X"
2. sort(Array.DESCENDING) 按字符串的倒序排列,区分大小写,数字也是按字符串来处理
- var arr:Array = ["b","C","a","X",235,8641,38];
- trace(arr.sort(Array.DESCENDING));//得到b,a,X,C,8641,38,235
3. sort(Array.UNIQUESORT) 同sort(),如果数组有相同元素,则放弃排序,返回0
- var arr:Array = ["b","C","a","X",235,8641,38,2365];
- if(arr.sort(Array.UNIQUESORT)=="0")
- {
- trace("有相同元素");
- }
- else
- {
- trace("没有相同元素");
- }
4. sort(Array.RETURNINDEXEDARRAY) 同sort(),返回排序后的索引列表,原数组不变
- var arr:Array = ["b","C","a","X",235,8641,38,2365];
- trace(arr.sort(Array.RETURNINDEXEDARRAY));//得到4,7,6,5,1,3,2,0
- trace(arr);//得到b,C,a,X,235,8641,38,2365(原数组)
5. sort(Array.NUMERIC) 按数字从小到大排序,如果数组里含有非数字,会抛出异常
- var arr:Array = [235,8641,38,2365];
- trace(arr.sort(Array.NUMERIC));//得到38,235,2365,8641
sort(函数名) 按自定义函数比较,该函数必须接受2个参数,返回值为1、-1、0
- public function Sample1008()
- {
- var objA:Object = {price:200,quantity:2};
- var objB:Object = {price:400,quantity:4};
- var objC:Object = {price:100,quantity:1};
- var arr:Array = [objA,objB,objC];
- trace("原数组是:");
- for(var i:int=0;i<arr.length;i++)
- {
- trace(arr[i].price);
- }
- arr.sort(Compare);
- trace("排序后的数组是:");
- for(var j:int=0;j<arr.length;j++)
- {
- trace(arr[j].price);
- }
- }
- private function Compare(paraA:Object,paraB:Object):int
- {
- var totalPriceA:int = paraA.price * paraA.quantity;
- var totalPriceB:int = paraB.price * paraB.quantity;
- if(totalPriceA>totalPriceB)
- {
- return 1;
- }
- else if(totalPriceA<totalPriceB)
- {
- return -1;
- }
- else
- {
- return 0;
- }
- }
- /*运行结果是
- 原数组是:
- 200
- 400
- 100
- 排序后的数组是:
- 100
- 200
- 400*/
热门文章推荐
- [Red5]Red5之Flash流媒体服务器的安装与使用教程完整版(组图)
- [rtsp]设置海康配置DDNS远程访问的用户手册(组图说明)
- [live555]live555直播rtsp流
- [HLS]做自己的m3u8点播系统使用HTTP Live Streaming(HLS技术)
- [FMS]FMS流媒体服务器配置与使用相关的介绍
- [FFmpeg]FFmpeg实现监控摄像头的RTSP协议转RTMP协议直播
- [海康]海康网络摄像机激活功能图文教程
- [RED5]搭建RED5直播用流媒体服务(搭直播环境)