js中数组(Array)的排序(sort)注意事项

直接看代码吧,测试结果也贴在里面了

《js中数组(Array)的排序(sort)注意事项》
var
 arrDemo 
=
 
new
 Array();
《js中数组(Array)的排序(sort)注意事项》
《js中数组(Array)的排序(sort)注意事项》 arrDemo[

0

=
 
10
;
《js中数组(Array)的排序(sort)注意事项》 arrDemo[

1

=
 
50
;
《js中数组(Array)的排序(sort)注意事项》 arrDemo[

2

=
 
51
;
《js中数组(Array)的排序(sort)注意事项》 arrDemo[

3

=
 
100
;
《js中数组(Array)的排序(sort)注意事项》
《js中数组(Array)的排序(sort)注意事项》 arrDemo.sort(); 

//
调用sort方法后,数组本身会被改变,即影响原数组

《js中数组(Array)的排序(sort)注意事项》


《js中数组(Array)的排序(sort)注意事项》 alert(arrDemo);

//
10,100,50,51 默认情况下sort方法是按ascii字母顺序排序的,而非我们认为是按数字大小排序

《js中数组(Array)的排序(sort)注意事项》


《js中数组(Array)的排序(sort)注意事项》《js中数组(Array)的排序(sort)注意事项》 arrDemo.sort(

function
(a,b)
《js中数组(Array)的排序(sort)注意事项》
{return a>b?1:1}
);
//
从小到大排序

《js中数组(Array)的排序(sort)注意事项》


《js中数组(Array)的排序(sort)注意事项》 alert(arrDemo);

//
10,50,51,100

《js中数组(Array)的排序(sort)注意事项》


《js中数组(Array)的排序(sort)注意事项》《js中数组(Array)的排序(sort)注意事项》 arrDemo.sort(

function
(a,b)
《js中数组(Array)的排序(sort)注意事项》
{return a<b?1:1}
);
//
从大到小排序

《js中数组(Array)的排序(sort)注意事项》


《js中数组(Array)的排序(sort)注意事项》 alert(arrDemo);

//
100,51,50,10

《js中数组(Array)的排序(sort)注意事项》

 

结论:

1.数组调用sort方法后,会影响本身(而非生成新数组)

2.sort()方法默认是按字符来排序的,所以在对数字型数组排序时,不可想当然的以为会按数字大小排序!

3.要改变默认的sort行为(即按字符排序),可以自行指定排序规则函数(如本例所示)

    原文作者:菩提树下的杨过
    原文地址: http://www.cnblogs.com/yjmyzz/archive/2009/10/20/1586896.html
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞