Update: Thank you for your support, recently toss a summary of information, convenient for you to read the system, there will be more content and more optimization, click here to view

—— The following is the text ——

The introduction

This installment begins with higher-order functions in JavaScript, where functions are a special type of object called Function objects. So what is a higher-order function? This section will expand the introduction through the definition of higher-order functions.

Higher-order functions

Higher-order function a higher-order function is a function that meets at least one of the following conditions:

  • Takes one or more functions as input
  • Output a function

That is, higher-order functions are functions that operate on other functions, either passing them as arguments or returning them. Simply put, a higher-order function is a function that either receives a function as an argument or outputs a function as a return value.

Functions are passed as arguments

The JavaScript language has some higher-order functions built in, such as array.prototype. map, array.prototype. filter, and array.prototype. reduce, that take a function as an argument, And apply this function to each element of the list. Let’s look at a scheme that uses them versus one that doesn’t use higher-order functions.

Array.prototype.map

The map() method creates a new array. The result is the result returned by each element in the array calling a provided function, leaving the original array unchanged. The callback passed to map takes three arguments currentValue, index (optional), array (optional), and this (optional) in addition to callback. The this value used when executing the callback function.

Taking a simple example, we now have an array [1, 2, 3, 4] and we want to generate a new array with each element twice as many as the previous array. We can do this in two ways, with and without higher-order functions.

Higher-order functions are not used

/ / wooden Yi Yang
const arr1 = [1.2.3.4];
const arr2 = [];
for (let i = 0; i < arr1.length; i++) {
  arr2.push( arr1[i] * 2);
}

console.log( arr2 );
// [2, 4, 6, 8]
console.log( arr1 );
// [1, 2, 3, 4]
Copy the code

Use higher-order functions

/ / wooden Yi Yang
const arr1 = [1.2.3.4];
const arr2 = arr1.map(item= > item * 2);

console.log( arr2 );
// [2, 4, 6, 8]
console.log( arr1 );
// [1, 2, 3, 4]
Copy the code

Array.prototype.filter

The filter() method creates a new array that contains all the elements of the test implemented by providing the function, leaving the original array unchanged. The parameters received are the same as the map, and the return value is a new array of all the elements that passed the test, or an empty array if none of the array elements passed the test.

As an example, we now have an array [1, 2, 1, 2, 3, 5, 4, 5, 3, 4, 4, 4] and we want to generate a new array that has no duplicates, i.e. de-duplicates.

Higher-order functions are not used

const arr1 = [1.2.1.2.3.5.4.5.3.4.4.4.4];
const arr2 = [];
for (let i = 0; i < arr1.length; i++) {
  if(arr1.indexOf( arr1[i] ) === i) { arr2.push( arr1[i] ); }}console.log( arr2 );
// [1, 2, 3, 5, 4]
console.log( arr1 );
// [1, 2, 1, 2, 3, 5, 4, 5, 3, 4, 4, 4]
Copy the code

Use higher-order functions

const arr1 = [1.2.1.2.3.5.4.5.3.4.4.4.4];
const arr2 = arr1.filter( (element, index, self) = > {
    return self.indexOf( element ) === index;
});

console.log( arr2 );
// [1, 2, 3, 5, 4]
console.log( arr1 );
// [1, 2, 1, 2, 3, 5, 4, 5, 3, 4, 4, 4]
Copy the code

Array.prototype.reduce

The reduce() method performs a provided Reducer function (ascending execution) on each element in the array, summarizing its results into a single return value. The callback function passed to Reduce takes four parameters: accumulator accumulator, currentValue, currentIndex (optional), array (optional), In addition to callback, you can also accept the initialValue initialValue (optional).

  • If no initialValue is provided, then accumulator uses the first element in the array when the callback function is called the first time, and currentValue is the second element in the array. Calling reduce on an empty array with no initial value will report an error.

  • If initialValue is provided, it will be the value of the first parameter when the callback function is called for the first time, which is accumulator. CurrentValue uses the first element in the original array.

Let’s take a simple example. We now have an array [0, 1, 2, 3, 4], and need to calculate the sum of the elements of the array.

Higher-order functions are not used

const arr = [0.1.2.3.4];
let sum = 0;
for (let i = 0; i < arr.length; i++) {
  sum += arr[i];
}

console.log( sum );
/ / 10
console.log( arr );
// [0, 1, 2, 3, 4]
Copy the code

Use higher-order functions

Without the initialValue value
const arr = [0.1.2.3.4];
let sum = arr.reduce((accumulator, currentValue, currentIndex, array) = > {
  return accumulator + currentValue;
});

console.log( sum );
/ / 10
console.log( arr );
// [0, 1, 2, 3, 4]
Copy the code

The above is the case where there is no initialValue. The code is executed as follows: Callback is called four times in total.

callback accumulator currentValue currentIndex array return value
first call 0 1 1 [0, 1, 2, 3, 4] 1
second call 1 2 2 [0, 1, 2, 3, 4] 3
third call 3 3 3 [0, 1, 2, 3, 4] 6
fourth call 6 4 4 [0, 1, 2, 3, 4] 10
Have the initialValue values

Let’s look at the case where we have an initialValue, let’s say initialValue is 10, and let’s look at the code.

const arr = [0.1.2.3.4];
let sum = arr.reduce((accumulator, currentValue, currentIndex, array) = > {
  return accumulator + currentValue;
}, 10);

console.log( sum );
/ / 20
console.log( arr );
// [0, 1, 2, 3, 4]
Copy the code

The code is executed as follows, with the callback called a total of five times.

callback accumulator currentValue currentIndex array return value
first call 10 0 0 [0, 1, 2, 3, 4] 10
second call 10 1 1 [0, 1, 2, 3, 4] 11
third call 11 2 2 [0, 1, 2, 3, 4] 13
fourth call 13 3 3 [0, 1, 2, 3, 4] 16
fifth call 16 4 4 [0, 1, 2, 3, 4] 20

Function is output as the return value

This is easy to understand, is to return a function, let’s look at two examples to understand.

IsType function

We know the type of time can be judged by the Object. The prototype. ToString. Call to get the corresponding Object returned string, such as:

let isString = obj= > Object.prototype.toString.call( obj ) === '[object String]';

let isArray = obj= > Object.prototype.toString.call( obj ) === '[object Array]';

let isNumber = obj= > Object.prototype.toString.call( obj ) === '[object Number]';
Copy the code

It can be found that the above three lines of code have a lot of duplicate code, just need to extract the specific type can be encapsulated into a method to determine the type, the code is as follows.

let isType = type= > obj= > {
  return Object.prototype.toString.call( obj ) === '[object ' + type + '] ';
}

isType('String') ('123');		// true
isType('Array') ([1.2.3]);	// true
isType('Number') (123);			// true

Copy the code

This is a higher-order function because the isType function obj => {… } this function is output as the return value.

The add function

Add = JS; add = JS; add = JS;

add(1); / / 1
add(1) (2);  / / 3
add(1) (2) (3);/ / 6
add(1) (2) (3) (4);/ / 10

// And so on

Copy the code

We can see that the structure is somewhat similar to the above code, which prints the function as a return value and then receives the new argument and evaluates it.

Add (a) returns a closure sum(b). Sum () computs a = a + b. Just rewrite sum.tostring () to return variable A.

function add(a) {
    function sum(b) { // Use closures
    	a = a + b; / / accumulation
    	return sum;
    }
    sum.toString = function() { // Override the toString() method
        return a;
    }
    return sum; // Return a function
}

add(1); / / 1
add(1) (2);  / / 3
add(1) (2) (3);/ / 6
add(1) (2) (3) (4);/ / 10

Copy the code

To consider

Given the following array, write a program to flatten the array and divide the duplicate part of the data, and finally get an ascending and non-repeating array

var arr = [ [1, 2, 2], [3, 4, 5, 5], [6, 7, 8, 9, [11, 12, [12, 13, [14] ] ] ], 10];

1. Flatten and de-weight

Refer to the article

Understand higher-order functions in JavaScript

Array.prototype.map()

Array.prototype.filter()

Array.prototype.reduce()

Article shuttle

  • [Advanced 5-3] Further explore the Function & Object egg problem

  • Step 5-2: Diagram prototype chains and their inheritance advantages and disadvantages

  • Reconceptualize constructors, stereotypes, and stereotype chains