实现自定义排序

本文介绍如何使用自定义排序函数对包含乐队名称的数组进行排序,通过去除乐队名称前的The来达到更合理的排序效果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

bands是一个歌曲名数组,在排序时忽略字符串中含有的"The" 字母

1.先看看默认的排序
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
2.自定义排序函数

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

var bands:Array = ["The Clash","The Who","Led Zeppelin",
"The Beatles","Aerosmith","Cream"];
bands.sort(bandNameSort); //传自定义函数bandNameSort
for(var i:int = 0; i < bands.length; i++)
{
trace(bands[i]);
}
/*输出
Aerosmith
The Beatles
The Clash
Cream
Led Zeppelin
The Who



private function bandNameSort(band1:String,band2:String):int
{
band1 = band1.toLowerCase();
band2 = band2.toLowerCase();
if(band1.substring(0,4)=="the ")
{
band1 = band1.substring(4);
}
if(band2.substring(0,4)=="the ")
{
band2 = band2.substring(4);
}
if(band1<band2)
{
return -1;
}
else
{
return 1;
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值