使用 array.reduce 方法计算 数组元素 对象的某个属性的总和时,存在一些问题
需要计算 数组元素的某个属性值的总和时,使用 array.reduce 计算时,当数组长度 大于 1 时,不存在问题;
数组样例: [{a: 1, b: 9}, {a: 2, b: 5}]
数组长度 大于 1时,计算正常
代码样例:
var tempArr = [{
a: 1,b: 9},{
a: 2,b: 5}];
var total = tempArr.reduce((pre, cur) => pre.a + cur.a);
console.log('total',total); // 3
长度 等于 1 时,直接返回元素
代码样例:
var tempArr = [{
a: 1,b: 9}];
var total = tempArr.reduce((pre, cur) => pre.a + cur.a);
console.log('total',total); // { a: 1, b: 9 }
若 数组长度 小于 2 时, array.reduce 不满足
优化 使用 array.map
故使用改用 array.map 方法
var tempArr = [{
a: 1,b: 9},{
a: 2,b: 5}];
var total = 0
tempArr.map(cur => total += cur.a)
console.log('total',total); // 3
注:
- 使用array.reduce 时, 数组长度 不能等于 0