function compare (prop) {
return function (obj1, obj2) {
var val1 = obj1[prop];
var val2 = obj2[prop];
if (!isNaN(Number(val1)) && !isNaN(Number(val2))) {
val1 = Number(val1);
val2 = Number(val2);
}
if (val1 < val2) {
return -1;
} else if (val1 > val2) {
return 1;
} else {
return 0;
}
}
}
使用
list =[{name:'aaa',sex:'bbbb',num:'20'},{name:'ds',sex:'fd',num:'22'},{name:'hyt',sex:'ghf',num:'3'}];
console.log(list.sort(compare("num")))