假设你有一个这样的JavaScript类
var DepartmentFactory = function(data) {
this.id = data.Id;
this.name = data.DepartmentName;
this.active = data.Active;
}
假设您随后创建了该类的许多实例,并将它们存储在一个数组中
var objArray = [];
objArray.push(DepartmentFactory({Id: 1, DepartmentName: 'Marketing', Active: true}));
objArray.push(DepartmentFactory({Id: 2, DepartmentName: 'Sales', Active: true}));
objArray.push(DepartmentFactory({Id: 3, DepartmentName: 'Development', Active: true}));
objArray.push(DepartmentFactory({Id: 4, DepartmentName: 'Accounting', Active: true}));
现在我将拥有一个由DepartmentFactory创建的对象数组。如何使用array.sort()方法按每个对象的DepartmentName属性对这个对象数组进行排序?
array.sort()方法在对字符串数组排序时工作得很好
var myarray=["Bob", "Bully", "Amy"];
myarray.sort(); //Array now becomes ["Amy", "Bob", "Bully"]
但是我如何让它与对象列表一起工作呢?
var DepartmentFactory = function(data) {
this.id = data.Id;
this.name = data.DepartmentName;
this.active = data.Active;
}
// use `new DepartmentFactory` as given below. `new` is imporatant
var objArray = [];
objArray.push(new DepartmentFactory({Id: 1, DepartmentName: 'Marketing', Active: true}));
objArray.push(new DepartmentFactory({Id: 2, DepartmentName: 'Sales', Active: true}));
objArray.push(new DepartmentFactory({Id: 3, DepartmentName: 'Development', Active: true}));
objArray.push(new DepartmentFactory({Id: 4, DepartmentName: 'Accounting', Active: true}));
function sortOn(property){
return function(a, b){
if(a[property] < b[property]){
return -1;
}else if(a[property] > b[property]){
return 1;
}else{
return 0;
}
}
}
//objArray.sort(sortOn("id")); // because `this.id = data.Id;`
objArray.sort(sortOn("name")); // because `this.name = data.DepartmentName;`
console.log(objArray);
演示:http://jsfiddle.net/diode/hdgeH/