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

查看:23
本文介绍了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'))

这能以一种方便的方式完成吗?谢谢.

Can this be done in a convenient way? thanks.

推荐答案

您需要部分申请 函数,例如使用 bind:

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

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

或者你只是让 compareOn 返回实际的排序函数,用外部函数的参数进行参数化(如其他函数所示).

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天全站免登陆