var
arrDemo
=
new
Array();
arrDemo[
0
]
=
10
;
arrDemo[
1
]
=
50
;
arrDemo[
2
]
=
51
;
arrDemo[
3
]
=
100
;
arrDemo.sort();
//
调用sort方法后,数组本身会被改变,即影响原数组
alert(arrDemo);
//
10,100,50,51 默认情况下sort方法是按ascii字母顺序排序的,而非我们认为是按数字大小排序
arrDemo.sort(
function
(a,b)
{return a>b?1:-1}
);
//
从小到大排序
alert(arrDemo);
//
10,50,51,100
arrDemo.sort(
function
(a,b)
{return a<b?1:-1}
);
//
从大到小排序
alert(arrDemo);
//
100,51,50,10
//字符串排序
var fn=function(a,b){
if(typeof(a)=="string"){
return a.localeCompare(b);
}
return a-b;
};
var arr=['张三','李四','王二','麻子'];
arr.sort(fn);
alert(arr);
结论:
1.数组调用sort方法后,会影响本身(而非生成新数组)
2.sort()方法默认是按字符(ASCII)来排序的,所以在对数字型数组排序时,不可想当然的以为会按数字大小排序!
3.要改变默认的sort行为(即按字符排序),可以自行指定排序规则函数(如本例所示)
本文详细介绍了JavaScript中数组sort方法的使用方式,包括其默认排序行为及如何通过自定义比较函数实现灵活排序,特别是对数字和字符串的不同排序逻辑。

132

被折叠的 条评论
为什么被折叠?



