JavaScript 高阶函数 sort对象传入指定 值排序
var persons= [
{ name:'john',age:23},
{ name:'Ada' ,age:41},
{ name:'zoo' ,age:3},
{ name:'Lemo',age:39}
]
function sortByname(obj1, obj2) {
if(obj1.name > obj2.name){
return 1;
}else if (obj1.name == obj2.name){
return 0;
}else {
return -1;
}
}
function sortByage(obj1, obj2) {
if(obj1.age > obj2.age){
return 1;
}else if (obj1.age == obj2.age){
return 0;
}else {
return -1;
}
}
function sortByproperty(properyName) {
var sortFun = function (obj1, obj2) {
if(obj1[properyName] > obj2[properyName]){
return 1;
}else if (obj1[properyName] == obj2[properyName]){
return 0;
}else {
return -1;
}
}
return sortFun
}
persons.sort(sortByproperty('age'))
for (var i = 0; i < persons.length; i++) {
console.log(persons[i]);
}