javascript reduce累加器使用
total
:每一次累加得到的结果
item
:循环列表中的当前项
index
:循环列表中的当前下标索引
arr
:循环列表中的当前下标索引
initialValue
:初始值
arr.reduce(function(total, item, index, arr){ }, initialValue)
- 基础列表类型
[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
- 数组包裹对象的数组
[{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
- 过滤特定类型
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