JavaScript is called a sort function

I was wondering if it is possible to pass a named function to Array.sort (). I am trying to do something like logic below, but obviously he complains that it is anot 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 make the code work as shown below, and it is, but I would prefer not to use anonymous functions for readability and debugging.

if (iWantToSortAscending) {
    myArray.sort(function (a, b) {
        ...
        sorty worty
        ....
    }
} else {
    ...
+4
source share
2 answers

Of course, but you need to refer to the function, not call it, and the arguments are passed automatically

myArray.sort(sortAscending);

, , .
, , , sort(), .

+5

, " ?"

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

? myArray.sort sortAscending(a,b). , a b , (ReferenceError). , a b ? sortAscending(a,b) .

, myArray.sort(sortAscending); - .

+4

All Articles