`

自定义排序

    博客分类:
  • flex
阅读更多

自定义数组排序
解决办法
把自定义比较的函数引用传递给sort( ) 方法
讨论
如果要自定义排序,可用sort( ) 方法和自定义比较函数。sort( ) 方法重复调用比较函数对两个数组元素进行比较,比较函数接受两个参数即数组元素(我们称为a和b),根据具体的排序方式返回正数,负数或0。如果返回负数,a排在b前,如果返回0,位置不变,如果返回正数,a排在b后,直到所有元素对比完毕。

下面有个例子对字符串数组进行自定义排序,比如是一个歌曲名数组,在排序时忽略字符串中含有的"The" 字母,首先看看默认的排序:

+展开
-ActionScript
var bands:Array = ["The Clash",
"The Who",
"Led Zeppelin",
"The Beatles",
"Aerosmith",
"Cream"];
bands.sort( );
for(var i:int = 0; i < bands.length; i++) {
trace(bands[i]);
/* 输出:
Aerosmith
Cream
Led Zeppelin
The Beatles
The Clash
The Who
*/

}


给sort( ) 方法传递bandNameSort 比较函数:

+展开
-ActionScript
var bands:Array = ["The Clash",
"The Who",
"Led Zeppelin",
"The Beatles",
"Aerosmith",
"Cream"];
bands.sort(bandNameSort);
for(var i:int = 0; i < bands.length; i++) {
trace(bands[i]);
/*输出
Aerosmith
The Beatles
The Clash
Cream
Led Zeppelin
The Who
*/

}
function bandNameSort(band1:String, band2:String):int
{
band1 = band1.toLowerCase( );
band2 = band2.toLowerCase( );
if(band1.substr(0, 4) == "the ") {
band1 = band1.substr(4);
}
if(band2.substr(0, 4) == "the ") {
band2 = band2.substr(4);
}
if(band1 < band2) {
return -1;
}
else {
return 1;
}
}


bandNameSort( ) 函数把字符串元素转换为小写,然后检测是否含有"The ",如果有则剪切掉,取剩余字符串进行比较

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics