javascript - map、filter、reduce区别及使用

定义和用法
  1. map()

    map() 方法返回一个新数组,数组中的元素为原始数组元素调用函数处理后的值。
    map() 方法按照原始数组元素顺序依次处理元素。

    注意: map() 不会对空数组进行检测。map() 不会改变原始数组。

  2. filter

    filter() 方法创建一个新的数组,新数组中的元素是通过检查指定数组中符合条件的所有元素。

    注意: filter() 不会对空数组进行检测。注意: filter() 不会改变原始数组。

  3. reduce

    reduce() 方法接收一个函数作为累加器,数组中的每个值(从左到右)开始缩减,最终计算为一个值。
    reduce() 可以作为一个高阶函数,用于函数的 compose。

    reduce() 对于空数组是不会执行回调函数的。

代码比较
let arr1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
let arr2 = [
  { id: 1, name: 'test1' },
  { id: 2, name: 'test2' },
  { id: 3, name: 'test3' },
  { id: 4, name: 'test4' },
  { id: 5, name: 'test5' }
]

let arrMap = arr1.map((item, index) => item > 2)
let arrFilter = arr1.filter((item, index) => item > 2)
let arrTotal = arr1.reduce((total, current, index) => {
  return total + current
}, 0)

console.log(arrMap) //[false, false, false,false, false, true,true,  true,  true,true]
console.log(arrFilter) //[ 6, 7, 8, 9, 10 ]
console.log(arrTotal) // 55 


let arrMap = arr2.map((item, index) => item.name)
let arrFilter = arr2.filter((item, index) => item.id > 4)
let arrTotal = arr2.reduce((total, current, index) => {
  return total + current.id
}, 0)

console.log(arrMap) //[ 'test1', 'test2', 'test3', 'test4', 'test5' ]
console.log(arrFilter) //[{ id: 5, name: 'test5' }]
console.log(arrTotal) // 15

总结

主要从以下几个点理解:

  1. map主要时用来构造我们需要的特定数据格式,比如像每个item添加属性,或者单纯获取某个属性值
  2. filter主要是用来过滤和筛选满足特定的条件下的值
  3. reduce主要是用于计算,当然他还有一些高级用法,此处不予说明
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值