javascript数组方法arr.reduce()累加器使用

javascript reduce累加器使用

total:每一次累加得到的结果
item:循环列表中的当前项
index:循环列表中的当前下标索引
arr:循环列表中的当前下标索引
initialValue:初始值

arr.reduce(function(total, item, index, arr){ }, initialValue)
  1. 基础列表类型 [number, number]
const arr = [1, 2, 3, 4]
const initVal = 0 //初始值

const result = arr.reduce((total, item, index, arr)=>{
    return total + item
}, initVal)
//(初始值)0 + 1 + 2 + 3 + 4
console.log('累加结果', result) //10
  1. 数组包裹对象的数组 [{a: number}, {a: number}]
const arr = [
    {n: 1},
    {n: 2},
    {n: 3},
    {n: 4},
]
const initVal = 0 //初始值
const result = arr.reduce((total, item, index, arr)=>{
    return total + item.n
}, initVal)

console.log('累加结果', result) //10
  1. 过滤特定类型
const arr = [
    {n: 1},
    {n: '文字'},
    {n: 3},
    {n: '文字'},
    {n: 5},
]
const initVal = 0 //初始值
const result = arr.reduce((total, item, index, arr)=>{
    if(typeof(item.n)=='number'){//只累加数字
        return total + item.n
    }
    return total//其他类型本次循环不进行累加操作
}, initVal)

console.log('累加结果', result) //9
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

来一颗砂糖橘

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值