Higher-order functions and callback functions

Higher-order functions: function (fn) Parentheses with function type arguments or return values are functions

     //
      function every(fn){
          fn(); // When a function is executed, its argument is a function that is executed during or after execution. This function is a callback of the original function
         // So callbacks are higher-order functions?
      }
//
Copy the code

Callback function: pass an executable piece of code to other code as an argument, and the code will be called at some point. This is called a callback. If the code is executed immediately, it is called a synchronous callback, and if it is executed at a later time, it is called an asynchronous callback.

doubt

Callbacks are higher-order functions, right?

Every: Checks whether an array element exists

Every 2. Every () stops iterating if one of the conditions is not met. The condition is the expression following the return

var data = [{'name':'0'.'age':'18'}, {'name':'1'.'age':'28'}, {'name':'2'.'age':'28'}]var res = data.every(function(elem, index, arr){
    console.log(elem);     / / only output {' name ':' 0 ', 'age', '18'}, {' name ':' 1 ', 'age' : '28'}
    // Because the second one returns false
    return elem.name == '0'
    console.log(elem);  If the expression after the return is correct or not, the next sentence is iterated if it is correct or not. If it is not, the next sentence is iterated directly.
    // If the return expression is correct or not, all statements following it will not be executed. If it is correct, it will be iterated again. If it is not, it will be iterated
})
Copy the code

So no matter whether the return expression is correct or not, all statements following it are not executed. If it is correct, it is iterated again, and if it is not correct, it is terminated

  1. The every() method is used to check whether all elements of an array meet the specified criteria (provided by a function).

    var data = [{ 'name': '0', 'age': '18' }, { 'name': '1', 'age': '28' }, { 'name': '2', 'age': '28' }] var res = data.every(function (elem, index, Return elem. Name == '0'}) console.log(res); / / output is falseCopy the code

Every rewriting

 Array.prototype.myEvery = function (fn) {
            var arr = this.// The data in data
                len = arr.length,
                args2 = arguments[1] | |window,
                res = true;

            for (var i = 0; i < len; i++) {
                if(! fn.apply(args2, [arr[i], i, arr])) { res =false;
                    break; }}return res;
        }

        var data = [ { name: '1'.age: '28' }, { name: '2'.age: '28' }];
        var res2 = data.myEvery(function (elem, index, array) {
            console.log(elem);
            return elem.name == '1' If ==0, only the first item of data will be output. If ==1, only two items will be output
        }, { name: 'jack' })    
        // every() == 'xx
        //return compares the value of data.
Copy the code

Every () == ‘xx

But what does argus2 do? It’s good to know the properties, but arrow functions will be useful in the future

Three.

The function of every is the same as that of every. The only difference is that the array stops traversal if one of the elements meets the condition, which is the expression after return

Popularly speaking, some stops when it encounters the correct one, and keeps repeating until it finds the correct one. Every if the first item is not correct, stops iterating, and continues iterating when the first item is correct

Some rewrite

        Array.prototype.mySome = function (fn) {
            var arr = this.// The data in data
                len = arr.length,
                args2 = arguments[1] | |window,
                res = false;

            for (var i = 0; i < len; i++) {
                if (fn.apply(args2, [arr[i], i, arr])) {
                    res = true;
                    break; }}return res;
        }

        var data = [ { name: '1'.age: '28' }, { name: '2'.age: '28' }, { name: '23'.age: '28' }];
        var res2 = data.mySome(function (elem, index, array) {
            console.log(elem);
            return elem.name == '0' / / o {name: '1', the age: '28'}, {name: '2', age: '28'}, {name: '23' age: '28'}
        }, { name: 'jack' })    
   // Stop when you find the right one, and continue until you find the wrong one
Copy the code

Iv. Reduce: Complete data induction

Returns a new array, placing the values that meet the criteria in the new array

The second reduce parameter must be filled in

 var data = [ { name: '1'.age: '28' }, { name: '2'.age: '28' }, { name: '23'.age: '28' }];
var initialValue = [];
var  nArr = data.reduce(function(prev, elem, index, arr){ // Separate the prev from the other three
   console.log(prev === initialValue);// Returns true, so prev and initialValue are the same thing
    return prev; // return prev; Undefined (the number of elements in the array, i.e. the number of times traversed)

}, initialValue)
Copy the code

1. Prev and initialValue are the same thing. The value of prev is taken from initialValue, so the second parameter must be filled in

2. The value must be returned, or the number of elements in the array -1, because the first return is true.

   var data = [{ name: '1'.age: '28' }, { name: '2'.age: '28' }, { name: '23'.age: '28' }];
   var initialValue = [];
   var nArr = data.reduce(function (prev, elem, index, arr) { // Separate the prev from the other three
       prev.push(elem.name); // Prev.push () is performed every time data.reduce is executed;
       console.log(prev); // Output ["1"], ["1", "2"], ["1", "2", "23"]
       return prev;

   }, initialValue)

Copy the code

Prev.push () is performed every time data.reduce is executed;

Reduce is essentially traversal, executing statements over and over again

  var data = [{ name: '1'.age: '28' }, { name: '2'.age: '28' }, { name: '23'.age: '28' }];
   var initialValue = [];
   var nArr = data.reduce(function (prev, elem, index, arr) { // Separate the prev from the other three
     
      if(elem.name === '1'){
          prev.push(elem);
       
      }
       return prev; // Returns the new array nArr

   }, initialValue)
  console.log(nArr); {name: "1", age: "28"}
Copy the code

So reduce and filter work in the same way, but in different ways: Reduce is done by induction, while filter is done by filtering: return Boolean true, not discard induction: In my condition, putting values into a new container (not the original container) will put everything that meets the condition into the new container

  var data = [{ name: '1'.age: '28' }, { name: '2'.age: '28' }, { name: '23'.age: '28' }];
   var initialValue = [];
   var nArr = data.reduceRight(function (prev, elem, index, arr) { // Separate the prev from the other three
          prev.push(elem);
       // console.log(elem);
       return prev;

   }, initialValue)
   console.log(nArr); / / output: {name: "23", the age: "28"}, {name: "2", the age: "28"}, {name: "1", the age: "28"}
   
Copy the code

Therefore, the only difference between reduceRight and Reduce is that the return result is inverted reduceRight is inverted sequence

conclusion

All array extension methods are iterated and looping in nature

Reduce is traversed from 0, and reduceRight is traversed from length (data.length-1)

The reduce of actual combat

Cookie data “name= 1; name2= 2 ; Change the name3= 23 “form to the object form

    
var cookieData =  " name= 1; name2= 2 ; name3= 23 " 
cookieArr = cookieData.split(";");
// console.log(cookieArr); [name= 1", "name2= 2 "," name3= 23 "]

var nArr = cookieArr.reduce(function(prev, elem){
    var item = elem.split('=');
       console.log(item); // Return three arrays
    // [" name", " 1"] [" name2", " 2 "] [" name3", " 23 "]
    
     prev [item[0]] = item[1];
     return prev;
}, {})                NArr returns an object because prev is an empty object
console.log(nArr); 
/ / o {" name ":" 1 ", "name2" : "2", "name3" : "23"}
Copy the code

[” name”, “1”] [” name2″,” 2″] [” name3″, “23 “] Because prev is an object, it changes the 0th entry of the array to the key name and the first entry to the key value, rendering the form name: 1

The reduce of rewriting


   Array.prototype.myReduce = function (fn, init) {
       var arr = this,
           len = arr.length,
           args2 = arguments[2] | |window;  // the subscript corresponding to init


       for (var i = 0; i < len; i++) {
           init = fn.apply(args2, [init, arr[i], i, arr]);
       }
       return init;
   }


   var cookieData = " name= 1; name2= 2 ; name3= 23 "
   cookieArr = cookieData.split(";");
   var nArr = cookieArr.myReduce(function (prev, elem) {
       var item = elem.split('=');
       // console.log(item); // Return three arrays
       prev[item[0]] = item[1];
       return prev;
   }, {})
   console.log(nArr);
Copy the code

Output more than {” name “:” 1 “, “name2” : “2”, “name3” : “23”} 1. Args2 = the arguments [2] | | window; {} 2. Init = fn.apply(args2, [init, arr[I], I, arr]); Put all the values returned from function into the second argument {}, and return the second argument

ReduceRight rewrite

The only difference is inside the for loop

       for (var i = len - 1; i >= 0; i--) {
            init = fn.apply(args2, [init, arr[i], i, arr]);
        }
        return init;
    }
Copy the code

The difficulties five.

Elem is the element in the call array and has nothing to do with this, so it can’t be the element in the array for the second argument