Example: function add(x, y, f) { return f(x) + f(y); } //Verify with code: add(-5, 6, Math.abs); // 11 1. Common higher-order functions 1.1、filter Example 1: Take out the data less than 100 in the array and put it into a new array let grad = [ 102, 188, 55, 66, 200, 800 ] let arr2 = grad.filter( function(item){ return item <= 100 }) console.log("arr2",arr2) // 55, 66 In the above example, the parameter passed to 1.2, mapMap means mapping. The original array is mapped into a new array, and the return value is a new array, without changing the original array. The length of the new array will not change with the original array. Example 2: Magnify each element of the data by 2 times. let arr2 = [ 55, 66 ] let arr3 = arr2.map( item => { return item*2 }) //Return result [110, 132] In the above example, the parameter received by 1.3、reduce Example 3: Sum the results returned by the previous example. let sum = arr3.reduce((tmp,item)=>{ return tmp+item }) //Return result 242 Now here comes the point. If we want to combine the above three examples together, how simple can we write it in the end? Responsible for writing: // Complex writing let grad = [102,188,55,66,200,800] let arr2 = grad.filter(function(item){ return item <= 100 }) let arr3 = arr2.map(item=>{ return item*2 }) let sum = arr3.reduce((tmp,item)=>{ return tmp+item }) Simple writing: //Simple writing let sum2 = grad .filter( item => {return item <= 100}) .map(item=>{return item*2}) .reduce((tmp,item)=>{return tmp+item}) This is the end of this article about the details of common higher-order functions You may also be interested in:
|
<<: Analysis of the process of building a LAN server based on http.server
>>: Bugs encountered when using mybatis-generator with mysql8.0.3 in IDEA
Often when building a SPA, you will need to prote...
This article mainly introduces the example of rea...
This article mainly introduces the solution to th...
Table of contents Preface What is index pushdown?...
Problem Record Today I was going to complete a sm...
CSS font properties define the font family, size,...
It is too troublesome to find the installation tu...
This article shares the specific code of Vue usin...
1. SSH remote management SSH is a secure channel ...
Overview Backup is the basis of disaster recovery...
Preface In LINUX, periodic tasks are usually hand...
In the past few years of my career, I have writte...
In the process of Django web development, when wr...
Achieve results html <h2>CSS3 Timeline</...
Table of contents Basic Edition Step 1: Configure...