Jquery将额外变量传递给sort函数

use*_*r10 5 javascript jquery

我需要编写一个常见的排序函数.我正在使用jQuery进行排序.jQuery sort函数只接受两个参数作为输入.但我想将另一个参数传递给该函数.我怎样才能做到这一点?

像这样的东西:

 obj.sort(StringSort);
 obj2.sort(StringSort);

 function StringSort(a, b, desc)
 {
    var aText = $(a).attr(desc).toLowerCase();
    var bText = $(b).attr(desc).toLowerCase();

    if(aText == bText)
      return 0;

    return aText > bText ? 1 : -1;
 }
Run Code Online (Sandbox Code Playgroud)

Fel*_*ing 12

您可以创建一个返回函数的函数.外部函数接受附加参数,并使用返回的函数作为排序回调:

function getStringSort(desc) {
    return function(a, b) {
        // this is a closure, you can access desc here
        // this function should contain your comparison logic or you just 
        // call StringSort here passing a, b  and desc.
    }
}

obj.sort(getStringSort(someValue));
Run Code Online (Sandbox Code Playgroud)

内部函数可以访问外部函数的所有参数,因为它是一个闭包[MDN].