可以直接看下效果
代码:
<script>
let list = [
{
num: 1,
price: 10,
},
{
num: 2,
price: 10,
},
{
num: 3,
price: 10,
},
{
num: 4,
price: 10,
},
]
// for循环 求总数和 num的和
let num = 0
for (let i = 0; i < list.length; i++) {
num += list[i].num
}
console.log('第一种:' + num);
// forEach 循环 num的和
let number = 0
list.forEach(v => {
number += v.num
});
console.log('第二种:' + number);
// reduce方法
let sum
sum = list.reduce((sum, obj) => (sum += obj.num), 0)
console.log('第三种:' + sum);
</script>
// 也可以直接封装一个方法 ,获取总量和总钱数
<script>
// 总价及数量
const totalData = function (data) {
const priceInfoObj = {};
priceInfoObj.totalNumber = data.reduce(
(totalNumber, obj) => (totalNumber += obj.num),
0,
);
priceInfoObj.priceSum = data.reduce(
(priceSum, obj) => (priceSum += obj.price * obj.num),
0,
);
return priceInfoObj
};
console.log(totalData(list))
</script>