JavaScript数组排序sort()

时间:2021-04-16 11:56:17   收藏:0   阅读:0

数组排序直接使用sort()

var values = [0,3,2,15,16,10];
//sort()排序 升序或者降序  默认升序
values.sort();  //[0, 10, 15, 16, 2, 3]

发现结果并不是想要的
原因:

//比较时会转换成字符串 比较的是ASCLL编码
var a = ‘10‘;
a.charCodeAt();  // 49
	
var b = ‘3‘;
b.charCodeAt();  // 51

数组排序sort()的正确使用

var values = [0,3,2,15,16,10];
//升序
function compare1(a,b){
    // a位于b之前
    if(a<b){
        return -1;
    }else if(a>b){
        return 1;
    }else{
        return 0;
    }
}
//降序
function compare2(a,b){
    // a位于b之前
    if(a<b){
        return 1;
    }else if(a>b){
        return -1;
    }else{
        return 0;
    }
}
values.sort(compare1); //升序
console.log(values); //[0, 2, 3, 10, 15, 16]

values.sort(compare2); //降序
console.log(values); //[16, 15, 10, 3, 2, 0]

简写

var values = [0,3,2,15,16,10];
//升序
function compare1(a,b){
   return a-b;
}
//降序
function compare2(a,b){
    return b-a;
}
values.sort(compare1); //升序
console.log(values); //[0, 2, 3, 10, 15, 16]

values.sort(compare2); //降序
console.log(values); //[16, 15, 10, 3, 2, 0]
评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!