1、原理
两个元素x和y,若x<y,返回-1;若x==y,返回0;若x>y,返回1。
2、对数字进行排序
var arr = [10,4,20,5,3];
//顺序排列
function ascSort(a,b) {
return a - b;
}
//倒序排列
function descSort(a,b) {
return b - a;
}
arr.sort(ascSort)//[3,4,5,10,10]
arr.sort(descSort)//[20,10,5,4,3]
//数组对象排序
varresult =[{title: "zx",score:5}, {title:"cyz",score:4}, {title:"wl",score:2}, {title:"zjw",score:3}, {title:"zzf",score:1}];
result.sort(getSortFun('asc','score'));
functiongetSortFun(order,sortBy) {
var ordAlpah = (order == 'asc') ? '>' : '<';
varsortFun = new Function('a', 'b', 'return a.'+ sortBy + ordAlpah + 'b.' + sortBy + ' ? 1: -1');
returnsortFun;
}//顺序排列
result.sort(getSortFun('desc', 'score'));
function getSortFun(order, sortBy) {
var ordAlpah = (order == 'asc') ? '>' : '<';
var sortFun = new Function('a', 'b', 'return a.' + sortBy + ordAlpah + 'b.' + sortBy + '? 1: -1');
return sortFun;
}//倒序排列