map/filter/reduce的用法

1、map是遍历数组的每一个值,在回调函数中进行修改

const arr = [1, 2, 3, 4, 5]
alert(arr.map((price) => {
    return price += 10
}))

最后输出结果为  11,12,13,14,15

2、filter的作用是筛选

const arr = [1, 2, 3, 4, 5]
alert(arr.filter((price) => {
    return price % 2 == 0
}))

输出结果为  2,4  

3、reduce最少需要两个参数

const arr = [1, 2, 3, 4, 5]
let num = arr.reduce((total,current) => {
    console.log(total,current)
    return current + total
})
console.log(arr, num)

输出结果为

1 2
3 3 
6 4
10 5
[1,2,3,4,5] 10

可以看到,total最开始是数组中第一个元素,而current为第二个元素,之后,current递增,而total则是累加的值,所以,第一次循环,total和current分别是arr[0]和arr[1],之后

在回调函数中进行一系列计算后,ruturn返回的值赋值给了total,下一次循环继续使用

posted @ 2020-06-18 16:23  渐行渐远9527  阅读(174)  评论(0)    收藏  举报