Ionic 3:如何计算数组集中值的总和

Ionic 3: How to calculate sum of values in sets of arrays

我有几组像这样的数组

我如何总结所有的 cartTotal?

我的ts文件代码是这样的

通过这种方法,我不断得到 0 作为答案

itemTotal() {
    let total = 0;
    for (var i = 0; i < this.bag.length; i++) {
      if (this.bag[i].cartTotal) {
        total += Number(this.bag[i].cartTotal);
      }
    }
    return total;
  }

我怎样才能做到这一点?

你只需使用 reduce

const total = this.bag.reduce((a,b) => a + b.cartTotal, 0);

您的代码中的错误是您需要访问 this.bagi 元素,而不是未定义的 this.bag.cartTotal[i]。 <-- 不存在,应该是 this.bag[i].cartTotal

cartTotal 是一个属性,在你的代码中你有一个数组,里面有多个对象。最简单的做法是:

let sum = 0;
for (let car of this.bag) {
  sum = sum + car.cartTotal;
 }
console.log(sum);

与 OP 交谈后,数据将按以下方式添加到 this.bag

this.storage.get('products').then(data => { 
 for (var i = 0; i < data.length; i++) { 
     //console.log(data[i]) 
     this.bag.push(data[i]); 
      } 
   });

由于 .then() 是异步调用的,因此在 .then() 之后使用 this.bag 的任何操作都不会 return 数据。

要解决此问题,请执行以下操作:

this.storage.get('products').then(data => 
{ 
  for (var i = 0; i < data.length; i++) 
  { 
   //console.log(data[i]) 
   this.bag.push(data[i]); 
  } 
this.itemChecks();
});

 itemChecks() 
 {
  for (let car of this.bag) { 
    this.sum = this.sum + car.cartTotal; 
    console.log(sum) 
  } 
}

您可以使用Array.prototype.reduce()进行计算。

喜欢

const total = [yourArray].reduce((total, nextObj) => {
  return total + nextObj.cartTotal;

}, 0);

console.log(total)

有关reduce函数的更多信息,请遵循指南。 Array.prototype.reuce()