//定义按字段排序的规则函数
function sortBy(name,sort){
console.log('name='+name+',sort='+sort);
return function(o, p){
var a, b;
if (typeof o === "object" && typeof p === "object" && o && p) {
a = parseInt(o[name]);
b = parseInt(p[name]);
if (a === b) {
return 0;
}
if(sort == 'asc'){
if (typeof a === typeof b) {
return a < b ? -1 : 1;
}
return typeof a < typeof b ? -1 : 1;
}else{
if (typeof a === typeof b) {
return a > b ? -1 : 1;
}
return typeof a > typeof b ? -1 : 1;
}
}
else {
throw ("error");
}
}
}
//定义要排序的对象
var employees=[]
employees[0]={name:"George", age:32, retiredate:"March 12, 2014"}
employees[1]={name:"Edward", age:17, retiredate:"June 2, 2023"}
employees[2]={name:"Christine", age:58, retiredate:"December 20, 2036"}
employees[3]={name:"Sarah", age:62, retiredate:"April 30, 2020"}
//进行按"age"元素排序 asc or desc
employees.sort(sortBy("age","asc"));
js根据数组中的某个字段排序
最新推荐文章于 2024-05-24 16:55:11 发布