0

我有一些这样的数组:

state = {
  array: [
    {
      id1,
      name1,
      price1
    },
    {
      id2,
      name2,
      price2
    },
    {
      id3,
      name3,
      price3
    }
  ]
}

然后我试图总结价格。

首先我试过 -

for (let key in arrayCopy) {
   totals += this.state.array[key].price;
}

第二个我试过=

for (let key in arrayCopy) {
   total[key] = this.state.array[key].price;
}
var totals = total.reduce((a,b) => a + b,0);

我将尝试用数字来解释它。例如:

price1 = 1000
price2 = 2000
price3 = 5000

我试图通过对所有价格求和来获得总结果。

totals = price1 + price2 + price3
totals = 8000

但我得到的结果是:

totals = 100020005000

有人可以指出我做错了什么吗?

4

2 回答 2

1

这是因为您price是 astring而不是 a number,您需要先将其转换为数字。

var totals = this.state.array.reduce((a,b)=>a+Number(b), 0);
于 2018-08-07T06:46:33.927 回答
0

使用 reduce Array 原型方法就足够了

 let items = [{id:1,name:'s', price:100},{id:2,name:'sew',price:50},{ id:3, name:'se',price:10}];

 let sum = items.reduce((a, b) => +a + +b.price, 0);

 console.log(sum);
于 2018-08-07T05:54:34.660 回答