数组reduce方法:
JS中数组提供了reduce的API来解决累加的问题,先看运行效果图
介绍
arr.reduce(callback,[initialValue])
callback:回调函数,执行数组中每个值 (如果没有提供 initialValue 则第一个值除外)的函数,包含四个参数:
accumulator:累计器累计回调的返回值; 它是上一次调用回调时返回的累积值,或initialValue。
currentValue:数组中正在处理的元素。
index(可选):数组中正在处理的当前元素的索引。 如果提供了initialValue,则起始索引号为0,否则从索引1起始。
array(可选):调用 reduce() 的数组
举例
[ 1,2,3,4,5 ].reduce( ( )=>{ }, 10 )
第一个参数是个回调,第二个参数是要累加的初始值,这里从10开始累加
回调中至少写两个参数,第一个代表初始值,第二个是当前元素,
第三个是索引,第四个是当前数组对象(第3、4个参数是可选的)
const result = [ 1,2,3,4,5 ].reduce( ( total, item,index,obj )=>{ return total + item }, 10 )
运行结果是 25
完整的代码实现:
const arr = [
{a: 5, b: 10, c: 20, msg: 'success'},
{a: 5, b: 10, c: 20, msg: 'warn'},
{a: 100, b: 100, c: 100, msg: 'error'}
];
console.log('数组:',arr);
let sum = {a:0, b:0, c:0, msg:0}
console.log('before:',sum);
for (let pos in sum) {
let total = arr.reduce((total, row) => { // 参数:累加初始值,当前对象
return total + parseInt(row[pos]) // 将每一行相同属性名累加起来
}, 0)
sum[pos] = !isNaN(total) ? total : '-' // 处理非数字(很重要)
}
console.log('after:',sum)
扩展:
这里和reduce没什么关系,记录一下方便以后用到
获取数组元素所有属性
let sum = {}
Object.keys(arr[0]).forEach((item) => {
Object.defineProperty(sum, item, {
value: 0,
writable: true,
enumerable: true,
configurable: true
})
})
这样可以拿到所有的属性名:a,b,c,msg
提取部分属性,使用JSON.stringify()
const arr2 = JSON.parse(JSON.stringify(arr, ['b', 'c']))
这样就提取到了属性值只有b和c的数据