打字稿数组总和而不是连接

时间:2017-09-27 07:51:04

标签: javascript loops typescript sum concatenation

我在打字稿中计算总和时出现问题,其中我有两个连接的数字,而不是将它们全部加起来。我已经查看了这个问题并且已经看到了几个涉及这个问题的主题,解决方案通常是这样的:

“使用ParseInt()ParseFloat()将字符串转换为整数”

问题是我没有字符串,即使我使用数字它们仍然连接。

我的代码如下:

     updateSummaryAmount(index: number){
        let summary = 0;

        this.listOfPeriods[index].declarations.forEach(element => {
            summary = summary + element.amount;
        });

        this.listOfPeriods[index].summary = summary;
    }

如果我总结

0,55

0,45

我得到了

00,550,45

当我尝试使用parseInt()或parseFloat时(0我得到以下打字稿错误:

[ts} Argument of type 'number'  is not assignable to parameter of type 'string'.

我试图与Math.floor()求和,只是为了测试,这样做有效,但显然让我没有想要的数字。

如何在我的案例中总结2个值?

1 个答案:

答案 0 :(得分:4)

尝试下面强制将element.amount更改为数字

this.listOfPeriods[index].declarations.forEach(element => {
  summary = summary + (+element.amount);
});