javascript - 使用 typescript 在 angular2 中进行加法运算

标签 javascript angular typescript addition

我编写了一个如下所示的组件:

export class AppComponent {
    public num1: number = 2;
    public num2: number = 3;
    public sum: number = 0;
    public add() {
        this.sum = this.num1 + this.num2;
    }
}

为此,我得到的总和为 23 而不是 5。请给我一个适当的解决方案来进行加法。 我很高兴知道答案

最佳答案

这是因为您的数字被视为字符串。

所以它的做法是“2”+“3”=“23”

要强制使用parseInt函数或执行...

this.sum = +this.num1 + +this.num2;

或者这也应该有效......

this.sum = +this.num1 + this.num2;

关于javascript - 使用 typescript 在 angular2 中进行加法运算,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40545241/

相关文章:

javascript - 是否可以在 D3.js 中使用日期范围作为时间刻度上的单独日期项目?

javascript - 使用 JavaScript 滚动到页面顶部?

typescript - 类型不匹配? "...is missing the following properties from type..."

typescript 提示解构类型

javascript - Chart.js – 如何从工具提示中删除数据条目?

javascript - 将字典键值添加到数组 [JavaScript]

css - 应用于 Angular 2 中父组件的子样式?

angular - 您如何捕捉错误

Angular 7路由连接导致编译错误

typescript - 将 react-router 与 typescript 一起使用