js sort()自定义函数如何传递更多参数? [英] js sort() custom function how can i pass more parameters?

查看:1220
本文介绍了js sort()自定义函数如何传递更多参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个对象数组,我需要对自定义函数进行排序,因为我想在几个对象属性上多次这样做,我想将属性的名称传递给自定义排序函数:

I have an array of objects i need to sort on a custom function, since i want to do this several times on several object attributes i'd like to pass the key name for the attribute dinamically into the custom sort function:

function compareOnOneFixedKey(a, b) {
    a = parseInt(a.oneFixedKey)
    b = parseInt(b.oneFixedKey)
    if (a < b) return -1
    if (a > b) return 1
        return 0
}

arrayOfObjects.sort(compareByThisKey)

应该是这样的:

function compareOnKey(key, a, b) {
    a = parseInt(a[key])
    b = parseInt(b[key])
    if (a < b) return -1
    if (a > b) return 1
        return 0
}
arrayOfObjects.sort(compareOn('myKey'))

这可以方便吗?谢谢。

推荐答案

你需要部分应用该功能,例如使用 bind

You would need to partially apply the function, e.g. using bind:

arrayOfObjects.sort(compareOn.bind(null, 'myKey'));

或者你只需​​要 compareOn 返回实际sort函数,使用外部函数的参数进行参数化(如其他函数所示)。

Or you just make compareOn return the actual sort function, parametrized with the arguments of the outer function (as demonstrated by the others).

这篇关于js sort()自定义函数如何传递更多参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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