1.定义函数
/** * 数组对象排序函数 * @param {any} name 排序字段 * @param {any} order 升、降(这里事true、false记得处理下) */ var by = function (name,order) { return function (o, p) { var a, b; if (typeof o === "object" && typeof p === "object" && o && p) { a = o[name]; b = p[name]; if (a === b) { return 0; } if (typeof a === typeof b) { if (order) { return a < b ? -1 : 1; } return a > b ? -1 : 1; } if (order) { return typeof a < typeof b ? -1 : 1; } return typeof a > typeof b ? -1 : 1; } else { throw ("error"); } } }
2.使用方式
//数组 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"} //调用 employees.sort(by("age"),true);