js比较函数

//1.
//bySort函数接受一个首要比较字符串和一个可选的次要比较函数做为参数
//并返回一个可以用来包含该成员的对象数组进行排序的比较函数
//当o[firstName] 和 p[firstName] 相等时,次要比较函数被用来比较
var bySort = function(compareName,minor){
return function(o,p){
var a,b;
if(o && p && typeof o === 'object' && typeof p ==='object'){
//如果是empty,用""表示
if(o.hasOwnProperty(compareName)){
a = o[compareName];
}
else{
a = "";
}
if(p.hasOwnProperty(compareName)){
b = p[compareName];
}
else{
b = "";
}
if(a === b){
return typeof minor === 'function' ? minor(o,p):0;
}
if(typeof a === typeof b){
return a < b ? -1:1;
}
return typeof a < typeof b ? -1 : 1;
}
}
}
function sortExtensionsByName(extensions){
extensions.sort(bySort('firstName',bySort('lastName'),bySort('ext')));
}

posted on 2019-02-27 11:30  IT-HourseMan  阅读(1822)  评论(0编辑  收藏  举报