当前位置:网站首页>Use of higher order functions

Use of higher order functions

2022-06-23 01:28:00 The opening of a midsummer night

The use of higher-order functions

Higher order function – The parameter of the function itself is also a function
filter/map/reduce
filter The callback function in has a requirement : Must return a boolean value .
If true when , The function will automatically call back this time n Add to a new array ; If you return false, The function will filter out the current n.

Example code used by the function :

// 1.filter Use of functions 
const nums = [1,22,11,3,300];
// n yes nums Elements in an array 
let newNums = nums.filter(function (n) {
    
	return n < 100; //  Will be bigger than the 100 Add elements of to newNums In the new array 
})

// 2.map Use of functions 
let new2Nums = newNums.map(function(n) {
    
	return n * 2; //  take newNums Every element in the array n, multiply 2 after , Return to array 
})

// 3.reduce Use of functions 
//  effect : Sum up all the contents of the array 
let total = new2Nmus.reduce(function (preValue, n) {
    
	return preValue + n
},0)
// numsNums = [2,44,22,6]
//  The first 1 Time : preValue=0; n=2
//  The first 2 Time : preValue=0+2=2; n=44
//  The first 3 Time : preValue=2+44=46; n=22
//  The first 4 Time :preValue=46+22=68; n=6


Simple writing

let total = newNums.filter(function (n) {
    
	return n < 100;
}).map(function (n) {
    
	return n * 2;	
}).reduce(function (preValue, n) {
    
	return preValue + n;
},0)

Easier to write :

let total = newNums.filter(n => n < 100).map(n => n*2).reduce((preValue, n) => preValue + n, 0);
//  perhaps  map Operations in functions , Can be placed reduce In the function 
let total = newNums.filter(n => n < 100).reduce((preValue, n) => preValue + n * 2, 0);

原网站

版权声明
本文为[The opening of a midsummer night]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202220521553091.html