【问题标题】:How can I multiply values in array to get the total sum? [duplicate]如何将数组中的值相乘以获得总和? [复制]
【发布时间】:2019-10-06 19:43:33
【问题描述】:

所以我有一个包含不同对象的数组,所有这些对象都包含一个名为“数量”的属性。我想将所有这些金额值加在一起以显示总金额

我尝试使用 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。

【问题讨论】:

  • 您可以使用reduce()this.totalItemCount = this.cart.reduce((ac,a) =&gt; a.amount + ac,0)

标签: javascript arrays typescript object ecmascript-6


【解决方案1】:

使用reduce:

    const arr = [{ amount: 3 }, { amount: 3 }];
    const res = arr.reduce((acc, { amount }) => acc + amount, 0);
    console.log(res);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-02-20
    • 2021-10-27
    • 2018-04-12
    • 1970-01-01
    • 2021-06-25
    • 1970-01-01
    • 2018-10-16
    • 1970-01-01
    相关资源
    最近更新 更多