This is the 25th day of my participation in the November Gwen Challenge. Check out the event details: The last Gwen Challenge 2021

Higher-order functions

Higher-order functions are functions that operate on other functions, taking functions as arguments or output functions as return values.

So f sub n is a higher order function

A function is also a data type that can also be passed as an argument to another argument. The most typical is as a callback function.

A function can also be passed back as a return value

closure

1. Review the scope of variables

Variables can be divided into two types depending on their scope: global variables and local variables.

  1. Global variables can be used inside functions.
  2. Local variables may not be used outside functions.
  3. Local variables in this scope are destroyed when the function completes execution.

2. What are closures

A closure is a function that has access to variables in the scope of another function. Simply put, a scope can access local variables inside another function.

3. What closures do

Action: Extend the scope of action of variables.

 function fn() {
   var num = 10;
   function fun() {
       console.log(num);
 	}
    return fun;
 }
var f = fn();
f();
Copy the code

4. The closure case

  1. Use closure to get the current li index
for (var i = 0; i < lis.length; i++) {
// Use the for loop to create four immediately executed functions
The immediate function is also a small closure because any function inside the immediate function can use its I variable
(function(i) {
    lis[i].onclick = function() {
      console.log(i);
    }
 })(i);
}
Copy the code
  1. Closure application – After 3 seconds, print the contents of all li elements
 for (var i = 0; i < lis.length; i++) {
   (function(i) {
     setTimeout(function() {
     console.log(lis[i].innerHTML);
     }, 3000)
   })(i);
}
Copy the code
  1. Closure application – Calculate taxi fares
/* Demand analysis Taxi fare starts at 13(within 3 kilometers) and increases by 5 yuan for each additional kilometer. Users input the mileage to calculate the price of the taxi. If there is congestion, an extra 10 yuan will be charged for the total price */

 var car = (function() {
     var start = 13; // Start price local variable
     var total = 0; // Total price local variable
     return {
       // Normal total price
       price: function(n) {
         if (n <= 3) {
           total = start;
         } else {
           total = start + (n - 3) * 5
         }
         return total;
       },
       // The cost after congestion
       yd: function(flag) {
         return flag ? total + 10: total; }}}) ();console.log(car.price(5)); / / 23
console.log(car.yd(true)); / / 33
Copy the code

Case 5.

 var name = "The Window";
   var object = {
     name: "My Object".getNameFunc: function() {
     return function() {
     return this.name; }; }};console.log(object.getNameFunc()())
-----------------------------------------------------------------------------------
var name = "The Window";varobject = {name: "My Object".getNameFunc: function() {
    var that = this;
    return function() {
    returnthat.name; }; }};console.log(object.getNameFunc()())
       
Copy the code

recursive

1. What is recursion

Recursion: A function is recursive if it can call itself internally. Simple to understand: a function that calls itself internally is a recursive function

Note: Recursive functions function as loops, recursion is prone to “stack overflow” error, so you must add an exit condition return.

2. Use recursion to find the factorial of 1~n

1 * 2 * 3 * 4 *... n
 function fn(n) {
     if (n == 1) { // End condition
       return 1;
     }
     return n * fn(n - 1);
 }
 console.log(fn(3));
Copy the code

3. Using recursion to find Fibonacci sequence

// Fibonacci sequence 1, 1, 2, 3, 5, 8, 13, 21...
// The user can input a number n to find the corresponding rabbit sequence value
// We only need to know the first two terms of the user input n (n-1 n-2) to calculate the corresponding sequence value of n
function fb(n) {
  if (n === 1 || n === 2) {
        return 1;
  }
  return fb(n - 1) + fb(n - 2);
}
console.log(fb(3));
Copy the code

4. Use recursion to iterate over data

// We want to make a data object that can be returned by typing an ID number
 var data = [{
   id: 1.name: 'goods'.goods: [{
     id: 11.gname: 'the refrigerator.goods: [{
       id: 111.gname: '海尔'
     }, {
       id: 112.gname: 'beauty']}, {},id: 12.gname: 'Washing machine'}]}, {id: 2.name: 'dress'
}];
//1. Use forEach to iterate through each object
 function getID(json, id) {
   var o = {};
   json.forEach(function(item) {
     // console.log(item); // 2 array elements
     if (item.id == id) {
       // console.log(item);
       o = item;
       return o;
       // 2. We want to get the data of the inner layer
       // There should be an array of goods and the array length is not zero
     } else if (item.goods && item.goods.length > 0) { o = getID(item.goods, id); }});return o;
}
Copy the code