您的位置:首页 > Web前端 > JavaScript

sort排序

2017-11-09 13:52 260 查看
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;
}//倒序排列
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  js