{ return b - a; }).join(",") } function upStr(str){//由大到小 return str.split(",").sort((a, b) => { return。js|js 字符串排序&json对象传入key值排序。" />

js|js 字符串排序&json对象传入key值排序

字符串排序 var year = "2018,2019,2000,2020,2006";
function downStr(str) {//由小到大
return str.split(",").sort((a, b) => { return b - a; }).join(",")
}
function upStr(str){//由大到小
return str.split(",").sort((a, b) => { return a - b; }).join(",")
}


yearArr.sort((a, b) => { return b - a; })


json对象传入key值排序
var arr = [{id:3},{id:6},{id:1},{id:2}];
arr.sort(downSort("id"));
function downSort(name) {//由小到大
return function (obj1, obj2) {
var value1 = obj1[name];
var value2 = obj2[name];
return value1 - value2;
}
}
var arr1 = [{id:3},{id:6},{id:1},{id:2}];
arr1.sort(upSort("id"));
function upSort(name) {//由大到小
return function (obj1, obj2) {
var value1 = obj1[name];
var value2 = obj2[name];
returnvalue2 - value1;
}
【js|js 字符串排序&json对象传入key值排序】}

    推荐阅读