1

I have written a custom sorting routine (sortArray(a, b)) to sort an array that I have.

If I call it like this

    a.sort(function (v1, v2) { return sortArray(v1, v2); });

everything works fine.

If I call it like this:

    a.sort(sortArray(v1, v2));

v1 and v2 raise errors, as being undefined.

Is there no way to utilize arguments passed by the .sort() method without creating an anonymous function to initially receive them, and then to pass them on to a user-defined function?

4

1 回答 1

6

Array.prototype.sort需要一个函数引用,但您正在尝试调用sortArray并传递该调用的返回值。您应该只传递对您的函数的引用:

a.sort(sortArray);

由于sortArray已经需要两个参数,它应该可以正常工作,v1并且v2会自动传递。

于 2013-07-29T15:20:37.390 回答