js 对象数组根据对象中的属性排序

           function createComparisonFunction(propertyName){
return function(object1,object2){
var value1 = object1[propertyName];
var value2 = object2[propertyName]; if(value1 < value2){
return -1;
}else if(value1 > value2){
return 1;
}else{
return 0;
}
};
}; var data = [{name:'Zacharty',age: 31},{name:'Nicholas',age: 29},{name:'Nicholas',age: 30}];
// 这里根据数组对象中的age属性排序
console.log(data.sort(createComparisonFunction('age')));
// [{name:'Nicholas',age: 29},{name:'Nicholas',age: 30},{name:'Zacharty',age: 31}]
上一篇:js 数组、对象转json 以及 json转 数组、对象


下一篇:C++_对象数组与对象指针