filter,map,reduce的基本使用

三种高阶函数filter,map,reduce的基本使用

在看这三个函数之前,我们先来看几个需求:

const nums = [10, 20, 30, 40, 100, 510, 300, 70, 999, 60]
//需求1:筛选出数组中小于100的数
let NewNum1 = [];
for (let n of nums){
if (n < 100)
NewNum1.push(n)
}
//需求2:将NewNum1数组中数据*2
let NewNum2 = [];
for (let n of NewNum1){
NewNum2.push(n * 2)
}
//需求3:将NewNum2中所有数据相加得到最终结果
let total = 0;
for (let n of NewNum2){
total += n
}

普通的解决办法就时用for循环遍历,filter,map,reduce三个函数就对应了这三个案例。

1、filter函数

filter(过滤器)起到一个过滤数据的作用,filter中的回调函数有一个要求:必须返回一个布尔值。当返回true时,函数内部会自动回调n进入数组,当返回false时,函数内部会过滤掉这次的n。:

const nums = [10, 20, 30, 40, 100, 510, 300, 70, 999, 60]
let NewNum1 = nums.filter(n => n < 100)
consloe.log(NewNum1)
//输出的结果为 [10, 20, 30, 40, 70, 60]

2、map函数

map函数是对数据进行映射操作,MDN web docsmap上说法是() 方法创建一个新数组,其结果是该数组中的每个元素都调用一个提供的函数后返回的结果。

//NewNum1 =[10, 20, 30, 40, 70, 60]
let NewNum2 = NewNum1.map(n => n * 2);
consle.log(NewNum2);
//输出结果为:[20, 40, 60, 80, 140, 120]

3、reduce函数

reduce函数每次的调用都会产生一个回调值,下一次调用将这个值作为参数,并进行累计,对数组中所有的内容进行汇总。

语法

array.reduce(function(prev, current, currentIndex, arr), initialValue)

prev:函数传进来的初始值或上一次回调的返回值
current:数组中当前处理的元素值
currentIndex:当前元素索引
arr:当前元素所属的数组本身
initialValue:传给函数的初始值

//NewNum2 = [20, 40, 60, 80, 140, 120]
let total = new4Nums.reduce(function (preValue, n) {
  return preValue + n
}, 0)
console.log(total2)
// 第一次:preValue: 0 ,n:20
// 第二次:preValue: 20 ,n:40
// 第三次:preValue: 60 ,n:60
// 第四次:preValue: 120 ,n:80
// 第五次:preValue: 200 ,n:140
// 第六次:preValue: 360 ,n:120
// total=460

猜你喜欢

转载自blog.csdn.net/qq_43588799/article/details/107971877