简体   繁体   中英

JavaScript named sort function

I was wondering if it's possible to pass a named function to Array.sort(). I'm trying to do something like the logic below but obviously it complains about a not being defined.

if (iWantToSortAscending) {
    myArray.sort(sortAscending(a, b));
} else {
    myArray.sort(sortDescending(a, b));
}

// my lovely sort functions
function sortAscending(a, b) {
    ...
    sorty worty
    ...
}

function sortDescending(a, b) {
    ...
    sorty worty differently
    ...
}

Obviously I could get the code to work like below, and it does, but I'd rather not be using anonymous functions for the sake of readability and debugging.

if (iWantToSortAscending) {
    myArray.sort(function (a, b) {
        ...
        sorty worty
        ....
    }
} else {
    ...

It sure is, but you have to reference the function, not call it, and arguments are passed automagically

myArray.sort(sortAscending);

whenever you add parentheses and arguments to a function, it's called immediately.
When you want it to be called by another function, for instance as a callback in sort() , you reference it, and leave the parentheses out.

Think "what is my program doing?"

myArray.sort(sortAscending(a, b));

What does it do? It tries to call myArray.sort with result of expression sortAscending(a,b) . First of all, a and b aren't defined, so it throws ( ReferenceError ). But what if a and b are defined? Result of expression sortAscending(a,b) wouldn't be a function.

To get things working, you have to use code myArray.sort(sortAscending); - it passes a function as argument.

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