【JS学习笔记】Array.sort 对包含任何值得简单数组排序

因为Array.sort默认比较函数把要排序的元素都视为字符串,所以无法正确地对数字排序。

简单的数组排序,例如:

n = ['aa','cc',12,56,2,'dd',14,79,3];
    n.sort(function (a, b) {
       if(a === b)
           return 0;
       if (typeof a === typeof b)
           return a<b ? -1 : 1;
       return typeof a < typeof b ? -1: 1;
    });
    for (var i=0; i < n.length; i++)
        document.writeln(n[i] + ", ");

输出结果:

对对象类数组排序,例如:

猜你喜欢

转载自blog.csdn.net/weixin_41835977/article/details/82983353