Javascript function as a parameter to another function?

后端 未结 7 1164
执念已碎
执念已碎 2021-01-31 06:17

I\'m learning lots of javascript these days, and one of the things I\'m not quite understanding is passing functions as parameters to other functions. I get the concept

7条回答
  •  Happy的楠姐
    2021-01-31 06:28

    I will illustrate is with sort scenario.

    Let's assume that you have an object to represent Employee of the company. Employee has multiple attributes - id, age, salary, work-experience etc.

    Now, you want to sort a list of employees - in one case by employee id, in another case by salary and in yet another case by age.

    Now the only thing that you wish to change is how to compare.

    So, instead of having multiple sort methods, you can have a sort a method that takes a reference to function that can do the comparison.

    Example code:

    function compareByID(l, r) { return l.id - r.id; }
    function compareByAge(l, r) { return l.age - r.age; }
    function compareByEx(l, r) { return l.ex - r.ex; }
    
    function sort(emps, cmpFn) {
       //loop over emps
       // assuming i and j are indices for comparision
        if(cmpFn(emps[i], emps[j]) < 0) { swap(emps, i, j); }
    }
    

提交回复
热议问题