Higher-order function: higher-order function JavaScript functions actually refer to a variable. Since variables can point to functions and arguments to functions can accept variables, a function can accept arguments to another function, which is called a higher-order function.

A higher-order function is one that satisfies at least one of the following conditions.

· Functions can be passed as arguments

· Functions can be output as return values

As an example, we want to create 100 div nodes on a page. This is one way to write it. We found that not all users wanted to display the 100 divs. So there’s a second way to write it

var appendDiv=function() {for(var i=0; i<100; i++){ var div =document.createElement('div'); div.innerHTML=i; document.body.appendChild(div); &emsp; &emsp; &emsp; &emsp; &emsp; &emsp; &emsp; div.style.display='block';
 } 
    
} 
appendDiv();
Copy the code

The second way to write it

This is where we pass in a function called appendDiv

function(node){
   node.style.display='none';
}

Copy the code

Then in appendDiv we decide if this is a function, and if so we execute it and pass it into appendDiv()

var appendDiv=function(callback){
    for(var i=0; i<100; i++){ var div =document.createElement('div');
        div.innerHTML=i;
        document.body.appendChild(div);
        if(typeof callback=='function'){
            callback(div);
            //console.log(callback);
        }
    }
}
appendDiv(function(node){
    node.style.display='none';
});

Copy the code

conclusion

div.style.display='block'; // This code is not reasonable, this code is put into the program is difficult to reuse, so we have to pass the function as an argument // the principle is like this,function(node){node.style.display='block'; // callback = var callback =function(node){
        node.style.display='block'; } callback(div); // Function executionCopy the code

Let me show you a simpler higher-order function

function add(x, y, f) {
    returnf(x) + f(y); } // when add(-5, 6, math.abs) is called, arguments x, y, and f receive -5, 6, and math.abs, respectively. //y = 6; //f = Math.abs; //f(x) + f(y) ==> Math.abs(-5) + Math.abs(6) ==> 11; //return11. // Add (-5, 6, math.abs); / / 11Copy the code

Let me introduce you to some higher-order functions

A, map/reduce

If you have read Google’s famous paper “MapReduce: Simplified Data Processing on Large Clusters”, you can get a sense of the concept of Map/Reduce. Since the map() method is defined in JavaScript Array, we call Array’s map() method, passing in our own function, and get a new Array as a result:

function pow(x) {
    returnx * x; } var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9]; arr.map(pow); [1, 4, 9, 16, 25, 36, 49, 64, 81] // Map () takes pow, the function object itself. // Write a loop to calculate the result without map() : var f =function (x) {
    return x * x;
};
var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];
var result = [];
for(var i=0; i<arr.length; i++) { result.push(f(arr[i])); } // We can, but we can't see from the loop above "apply f(x) to each element of the Array and generate a new Array".Copy the code

So, map(), being a higher-order function, actually abstracts the operation rules, so that we can compute not only simple f(x)=x2, but also arbitrarily complex functions, such as converting all Array numbers to strings:

var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9]; arr.map(String); / / /'1'.'2'.'3'.'4'.'5'.'6'.'7'.'8'.'9'] // Just one line of code.Copy the code

2, the reduce () :

Now look at the use of reduce. Array reduce() applies a function to Array [x1, x2, x3…]. The function must take two arguments, reduce(), and continue the cumulative calculation with the next element of the sequence, resulting in:

[x1, x2, x3, x4]. Reduce (f) = f(f(f(x1, x2), x3), x4) arr.reduce(function (x, y) {
    returnx + y; }); / / 25Copy the code

Second, the filter

Filter is also a common operation to filter out some elements of an Array and return the rest. Like map(), filter() of Array receives a function. Unlike map(), filter() applies the passed function to each element in turn, and then decides whether to keep or discard the element depending on whether the value returned is true or false.

Var arr = [1, 2, 4, 5, 6, 9, 10, 15]; var arr = [1, 2, 4, 5, 6, 9, 10, 15] var r = arr.filter(function (x) {
    returnx % 2 ! = = 0; }); r; Var arr = [1, 5, 9, 15];'A'.' '.'B', null, undefined, 'C'.' '];
var r = arr.filter(function (s) {
    returns && s.trim(); // Note: Versions below IE9 do not have the trim() method}); arr; / / /'A'.'B'.'C']
Copy the code

The key to using filter() is to implement a filter function correctly.

Callback function: filter() receives a callback function that can take multiple arguments. Usually we just use the first parameter, which represents an element of the Array. The callback can also take two additional arguments that represent the position of the element and the array itself:

var arr = ['A'.'B'.'C'];
var r = arr.filter(function(element, index, self) { console.log(element); // Print in sequence'A'.'B'.'C'console.log(index); // Print 0, 1, 2 console.log(self); // self is the variable arrreturn true; }); // Use filter to subtly remove duplicate elements from Array:'use strict';
var r,
    arr = ['apple'.'strawberry'.'banana'.'pear'.'apple'.'orange'.'orange'.'strawberry'];
r = arr.filter(function (element, index, self) {
    returnself.indexOf(element) === index; }); alert(r.toString()); // Removing duplicate elements depends on the fact that indexOf always returns the position of the first element. Subsequent duplicate elements are not equal to the position returned by indexOf and are therefore filtered out by filter.Copy the code

A sort algorithm

Because Array’s sort() method defaults to converting all elements to String before sorting, the result is ’10’ before ‘2’ because character ‘1’ is smaller than ASCII character ‘2’. If you don’t know the default sort rule for the sort() method and sort by numbers, you’re in for a dead end!

Fortunately, the sort() method is also a higher-order function, which can also accept a comparison function for custom sorting.

Var arr = [10, 20, 1, 2]; arr.sort(function (x, y) {
    if (x < y) {
        return- 1; }if (x > y) {
        return 1;
    }
    return0; }); Var arr = [10, 20, 1, 2]; var arr = [10, 20, 1, 2]; arr.sort(function (x, y) {
    if (x < y) {
        return 1;
    }
    if (x > y) {
        return- 1; }return0; }); [20, 10, 2, 1] // By default, strings are sorted alphabetically, regardless of case. Var arr = [var arr = [var arr = [var arr = [var arr = ['Google'.'apple'.'Microsoft'];
arr.sort(function (s1, s2) {
    x1 = s1.toUpperCase();
    x2 = s2.toUpperCase();
    if (x1 < x2) {
        return- 1; }if (x1 > x2) {
        return 1;
    }
    return0; }); / / /'apple'.'Google'.'Microsoft'] // To compare two strings regardless of case, you actually make both strings uppercase (or lowercase) first and then compare. // the sort() method modifs the Array directly and returns the same result as the current Array: var a1 = ['B'.'A'.'C']; var a2 = a1.sort(); a1; / / /'A'.'B'.'C'] a2; / / /'A'.'B'.'C']
a1 === a2; // trueA1 and A2 are the same objectCopy the code