一、普通数组排序
js中用方法sort()为数组排序。sort()方法有一个可选参数,是用来确定元素顺序的函数。如果这个参数被省略,那么数组中的元素将按照ASCII字符顺序进行排序。如:
<pre style="margin-top: 0px; margin-bottom: 0px; white-space: pre-wrap; word-wrap: break-word; font-family: "Courier New" !important; font-size: 12px !important; max-width: 600px;">var arr = ["a", "b", "A", "B"];
arr.sort();
console.log(arr);//["A", "B", "a", "b"]</pre>
因为字母A、B的ASCII值分别为65、66,而a、b的值分别为97、98,所以上面输出的结果是 ["A", "B", "a", "b"] 。
如果数组元素是数字呢,结果会是怎样?
<pre style="margin-top: 0px; margin-bottom: 0px; white-space: pre-wrap; word-wrap: break-word; font-family: "Courier New" !important; font-size: 12px !important; max-width: 600px;">var arr = [15, 8, 25, 3];
arr.sort();
console.log(arr);//[15, 25, 3, 8]</pre>
结果是 [15, 25, 3, 8] 。其实,sort方法会调用每个数组项的toString()方法,得到字符串,然后再对得到的字符串进行排序。虽然数值15比3大,但在进行字符串比较时"15"则排在"3"前面。显然,这种结果不是我们想要的,这时,sort()方法的参数就起到了作用,我们把这个参数叫做比较函数。
比较函数接收两个参数,如果第一个参数应该位于第二个之前则返回一个负数,如果两个参数相等则返回0,如果第一个参数应该位于第二个之后则返回一个正数。例子:
](
http://upload-images.jianshu.io/upload_images/3144381-4fc32ae01c100737.gif?imageMogr2/auto-orient/strip)](javascript:void(0)
; "复制代码")
<pre style="margin-top: 0px; margin-bottom: 0px; white-space: pre-wrap; word-wrap: break-word; font-family: "Courier New" !important; font-size: 12px !important; max-width: 600px;">var arr = [23, 9, 4, 78, 3]; var compare = function (x, y) {//比较函数 if (x < y) { return -1;
} else if (x > y) { return 1;
} else { return 0;
console.log(arr.sort(compare)); </pre>