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

js,jquery 根据对象某一属性进行排序

2015-03-24 10:56 751 查看
核心代码

//针对对象数据进行排序propertyName 要排序的属性名,order 1为正序0为倒序
function compare(propertyName,order) {
return function (object1, object2) {
var value1 = object1[propertyName];
var value2 = object2[propertyName];
if(order==0){
if (value2 < value1) {
return -1;
}
else if (value2 > value1) {
return 1;
}
else {
return 0;
}
}if(order==1){
if (value2 > value1) {
return -1;
}
else if (value2 < value1) {
return 1;
}
else {
return 0;
}
}

}
}


用法

//打印在console中
console.log(list.sort(compare("propertyName",0)));


其中 list是要排序的集合 sort是js内置排序方法,compare 自定义的排序方法,propertyName是要排序的对象属性,0是正序 1是倒序
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: