1 //javaScript sort()排序算法
2 //sort()方法默认把所有的元素转换成String再排序,字符串是根据ASCII进行排序的,所以会出现“10”排在“2”前面,或是小写字母“a”排在大写“B”的后面等情况。、
3
4 //可以通过接收一个比较函数来实现自定义的排序。
5 /*1*/
6 var arr=[10,20,1,2];
7 arr.sort(function(x,y){
8 if(x<y){
9 return -1;
10 }
11 if(x>y){
12 return 1;
13 }
14 return 0;
15 });
16 console.log(arr);//[1, 2, 10, 20]
17
18
19 /*2*/
20 var arr=[10,20,1,2];
21 arr.sort(function(x,y){
22 if(x>y){
23 return -1;
24 }
25 if(x<y){
26 return 1;
27 }
28 return 0;
29 });
30 console.log(arr);//[20, 10, 2, 1]
31
32 /*3*/
33 //对字符串按字母顺序进行排序。实际上就是把字符串都变成大写(或者是都变成小写),再比较。
34 var arr = ['Google', 'apple', 'Microsoft'];
35 var a=arr.sort(function(s1,s2){
36 x1=s1.toUpperCase();
37 x2=s2.toUpperCase();
38 if(x1<x2){
39 return -1;
40 }
41 if(x1>x2){
42 return 1;
43 }
44 return 0;
45 });
46 console.log(a);//["apple", "Google", "Microsoft"]
47
48 //要注意的是:sort()方法会直接对Array进行修改,它返回的结果仍是当前Array。
49 console.log(arr);// ["apple", "Google", "Microsoft"]