简体   繁体   中英

Arguments Provided to an Anonymous Function

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?

Array.prototype.sort expects a function reference, but you are trying to call sortArray and pass the return value of that call. You should just pass a reference to your function:

a.sort(sortArray);

Since sortArray already expects two arguments, it should just work, v1 and v2 will be passed automatically.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM