所以我有一个包含differents对象的数组,所有这些对象都包含一个称为“ amount”的属性。我想将所有这些金额值加在一起以显示总金额
我已经尝试过使用for循环,但是在这里我说“ this.totalItemCount = this.cart [i] .amount;”但这只会给我该特定对象的数量。
(2) [{…}, {…}]
0: {movie: {…}, amount: 3}
1: {movie: {…}, amount: 3}
length: 2
循环
totalItemCount: number;
addMovie(movie: IMovie) {
let foundMovie = false;
for (let i = 0; i < this.cart.length; i++) {
if (movie.id === this.cart[i].movie.id) {
this.cart[i].amount++;
foundMovie = true;
this.totalItemCount = this.cart[i].amount;
console.log(this.totalItemCount)
}
}
我希望变量“ totalItemCount”显示为6。
答案 0 :(得分:1)
使用reduce
:
const arr = [{ amount: 3 }, { amount: 3 }];
const res = arr.reduce((acc, { amount }) => acc + amount, 0);
console.log(res);