代码之家  ›  专栏  ›  技术社区  ›  Angulandy2

有角度的2个对象数组每个对象得到一个值(5+5=10)

  •  0
  • Angulandy2  · 技术社区  · 7 年前

    我得到了一系列类似这样的物体;

    array [
    0 { price: 15 }
    1 { price:18 }
    ]
    

    我想得到所有的价格,然后写一个总结=15+18=

      export class CartItems {
        price: number;
        }
     cartItems: CartItems[];
    this.cartItems = this.cart.products; // I get array from my service
    

    HTML(我可以得到每个价格):

    <div *ngFor="let cart of cartItems; let i = index">
    <p>{{cart.price}}
    </div>
    <div> Here I want my summ of all prices to be </div>
    

    如何得到所有价格的总和?

    2 回复  |  直到 7 年前
        1
  •  3
  •   Lia    7 年前

    ts码:

    this.sum = this.cartItems.reduce((a, b) => +a + +b.price, 0);
    

    html格式:

    <div *ngFor="let cart of cartItems; let i = index">
    <p>{{cart.price}}
    </div>
    <div>{{sum}}</div>
    
        2
  •  0
  •   P.S.    7 年前

    你可以使用 Array.prototype.reduce() 迭代方法并得到两个元素的和,传递给回调函数。你的情况应该是这样的:

    const array = [
      {
        price: 15
      },
      {
        price: 18
      }
    ];
    const sum = array.reduce((a, b) => a + b.price, 0);
    console.log(sum);

    在提供的示例中,您只有 number 类型,但对于保险您可以添加 + 在将项目转换为数字之前:

    const sum = array.reduce((a, b) => +a + +b.price, 0);