在JavaScript中排序自定义对象的数组 [英] Sorting array of custom objects in JavaScript

查看:56
本文介绍了在JavaScript中排序自定义对象的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有一组雇员对象:

var Employee = function(fname, age) {
    this.fname = fname;
    this.age = age;
}

var employees = [
    new Employee("Jack", "32"),
    new Employee("Dave", "31"),
    new Employee("Rick", "35"),
    new Employee("Anna", "33")
];


在这一点上, employees.sort()毫无意义,因为解释器不知道如何对这些自定义对象进行排序.因此,我传入了自定义排序功能.

At this point, employees.sort() means nothing, because the interpreter does not know how to sort these custom objects. So I pass in my custom sort function.

employees.sort(function(employee1, employee2){
    return employee1.age > employee2.age;
});


现在 employees.sort()可以正常工作了.


Now employees.sort() works dandy.

但是,如果我还想控制要排序的字段,并在运行时以某种方式传递该字段怎么办?我可以这样做吗?

employees.sort(function(employee1, employee2, on){
    if(on === 'age') {
        return employee1.age > employee2.age;
    }
    return employee1.fname > employee2.fname;
});

我无法使用它,所以有建议吗?也许是基于设计模式的重构?

I can't get it to work, so suggestions? Design pattern based refactoring perhaps?

推荐答案

function getSortFunction(fieldName) {
    return function(employee1, employee2) {
        return employee1[fieldName] > employee2[fieldName];
    }
}

employees.sort(getSortFunction("myField"));

另一种解决方案是使用 Function.prototype.bind 如果您不害怕的话:)

Another solution is to use Function.prototype.bind if you are not afraid of it :)

function mySorter(fieldName, employee1, employee2) {
    return employee1[fieldName] > employee2[fieldName];
}

employees.sort(mySorter.bind(null, "myField"));

这篇关于在JavaScript中排序自定义对象的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆