js commonly used higher-order functions (filter, map, reduce ...)

let nums = [10,30,50,100,110,300];
1.filter (fn)
Function: Filter, fn is a function that returns a true / false, when retained within the array value is true, otherwise removed
Objective: To screen 100 or less
let nums1 = nums.filter(function(n){
   return n < 100; 
 });
let nums1 = nums.filter(n => n<100)
The results [10,30,50]

2.map(fn)
Function: to carry out fn for each member of the array, the array is returned
Objective: double array value
let nums3 = nums.map(function(n){
   return n*2;
});
let nums3 = nums.map(n => n*10);
The results [100, 300,500,1000,1100,3000]

3.reduce (fn (a, b) {}, the initial value)
功能:类似递归,a为初始值代入,其值返回一个数值c,再次代入fn(a,b),最后得到结果
目的:数组和
let nums4 = nums.reduce(function (pre,n) {
   return n + pre;  
},100);
let nums4 = nums.reduce((m,n) => m+n,100);
结果600

Guess you like

Origin www.cnblogs.com/xiaoguniang0204/p/12292348.html