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;
}
}
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;
}
}