Array排序方法sort()中的大坑

sort() 方法用于对数组的元素进行排序。

但是排序结果就有点坑了,都不按常规出牌的:

// 看上去正常的结果:
['Google', 'Apple', 'Microsoft'].sort(); // ['Apple', 'Google', 'Microsoft'];

// apple排在了最后:
['Google', 'apple', 'Microsoft'].sort(); // ['Google', 'Microsoft", 'apple']

// 无法理解的结果:
[10, 20, 1, 2].sort(); // [1, 10, 2, 20]

1、对了,跟想像中一样;
2、是因为字符串根据ASCII码进行排序,而小写字母a的ASCII码在大写字母之后,可以理解;
3、什么鬼?三岁小孩都不会错,现在居然...emoticon

看了大神的一些讲解是:
因为Array的sort()方法默认把所有元素先转换为String再排序,结果'10'排在了'2'的前面,因为字符'1'比字符'2'的ASCII码小。
还好有大神讲解,不然掉了sort()的坑都不知怎么爬上来。

数字大小排序,就要用比较方法来写了:

var arr = [10, 20, 1, 2];
//方法一
function sortNum01(x, y) {
    if (x < y) {
        return -1;
    }
    if (x > y) {
        return 1;
    }
    return 0;
};


//方法二
function sortNum02(x, y) {
    return x -y;
};

alert(arr.sort(sortNum01))// [1, 2, 10, 20]
alert(arr.sort(sortNum02))// [1, 2, 10, 20]

忽略大小写,按照字母序排序(先把字符串都变成大写或者都变成小写比较,对原来arr没影响):

var arr = ['Google', 'apple', 'Microsoft'];
arr.sort(function (s1, s2) {
    x1 = s1.toUpperCase();
    x2 = s2.toUpperCase();
    if (x1 < x2) {
        return -1;
    }
    if (x1 > x2) {
        return 1;
    }
    return 0;
}); 
alert(arr);// ['apple', 'Google', 'Microsoft']

原文地址:http://www.qdfuns.com/notes/34750/0aadfcc0dde6a36ca9ab59613d285102.html

慎于行,敏于思!GGGGGG
原文地址:https://www.cnblogs.com/GarsonZhang/p/7977047.html