【问题标题】:I want to get total of items price but it doesn't show any value in ionic 4我想获得物品的总价格,但它在 ionic 4 中没有显示任何价值
【发布时间】:2020-07-21 19:47:16
【问题描述】:
this.stor.get('cart').then(val => {
  var sum = 0;
  this.data = val;
  for (let i = 0; i <= this.data.length; i++) {
    this.data[i].total = this.data[i].price * this.qty;
    sum = sum + this.data[i].total;

  };

  console.log(sum)

})

我想得到我购物车中每件商品的总数我使用了这个函数,如果我在循环中控制台求和,它将根据每个第 i 个值在循环中给出正确的值,而不是在循环之外。哪里出错了请告诉我谢谢

【问题讨论】:

  • 试试let sum: number = 0而不是var;

标签: angular ionic-framework ionic3 ionic4 shopping-cart


【解决方案1】:

试试这个。

this.data = val;
const sum = this.data.reduce((result, currentValue) => {
  currentValue['total'] = currentValue.price * this.qty;
  return result + currentValue['total'];
}, 0);

console.log(sum);
console.log(data);

【讨论】:

    【解决方案2】:

    试试这个方法:

    let sum: number = 0;
    
    this.data.map((val) => {
      val.total = val.price * val.qty; // this will update your total key
      sum += val.total; // this will add total to your sum
    });
    
    console.log(sum);
    

    【讨论】:

      【解决方案3】:

      我所学的这个函数推荐用于列表中的总和

       getTotal = () => {
              return this.{{**card list**}}.map(t => t.price).reduce((acc, value) => acc + value, 0)
            }
      

      【讨论】:

        猜你喜欢
        • 2019-07-19
        • 2013-11-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-06-08
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多