javascript - typescript : Trying the addition of two variables but get the concatenation of the two

标签 javascript typescript addition

我的 Typescript 类中有三个变量:

A:number;
B:number;
C:number;

在类(class)的另一部分,我尝试添加两个变量 A 和 B:

this.C = this.A+this.B; // A =20 and B = 50;

我在html模板中显示C

<span>{{C}}</span>

我的问题是,我没有得到两个变量 (20+50=70) 的加法,而是得到了连接 (2050)!!

有人可以帮帮我吗?

更新:

这是导致问题的确切代码部分:

goTo(page:number,type:script) {
    //    
    this.pageFirstLineNumber = page;
    this.pageLastLineNumber = page + this.LINE_OFFSET; //concatenation!!
}

注意 pageLastNumber 被声明为数字类型,LINE_OFFSET 是其他数字类型,我找到了解决这个问题的方法,但是 typescript 编译器输出错误(禁止 eval):

////
....
this.pageFirstLineNumber = eval(page.toString()); // now It works !!
this.pageLastLineNumber = page + this.LINE_OFFSET; //concatenation!!

更新

这里是 LINE_OFFSET 变量的声明:

private _calculateOffset(fontSize: number) {
    let linesDiff = (fontSize * 27) / 14;
    let lines:number = 27 - (linesDiff - 27);
    this.LINE_OFFSET = Math.floor(lines);
    if (fontSize >= 17 && fontSize <= 20) {
        this.LINE_OFFSET += (Math.floor(fontSize / 3) - 2);
    }
    if (fontSize > 20 && fontSize <= 23) {
        this.LINE_OFFSET += (Math.floor(fontSize / 2) - 2);
    }
    if (fontSize > 23 && fontSize <= 25) {
        this.LINE_OFFSET += (Math.floor(fontSize / 2));}
    if (fontSize > 25 && fontSize <= 27) {
        this.LINE_OFFSET += (Math.floor(fontSize / 2) + 1);
    }
    if (fontSize > 27 && fontSize <= 30) {
        this.LINE_OFFSET += (Math.floor(fontSize / 2) + 4);
    }
}

最佳答案

在数字前加上 +:

let a = +b + +c;

ref

关于javascript - typescript : Trying the addition of two variables but get the concatenation of the two,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39269701/

相关文章:

Typescript 完全限定命名空间与导入有什么区别

node.js - TypeError : Reflect. hasOwnMetadata 不是函数

javascript - 为什么我无法添加到数字对象属性?

php - 在MySQL中添加使用列中的信息来创建变量?

javascript - 如何使用 Jquery 中的 onclick 按钮在多个 div 上使用显示和隐藏

javascript - 为什么 Google Visualization 会导致 HTML1504 Unexpected end tag 错误?

javascript - 从文本文件加载 json 数据时出现空白页

html - 在 Angular 8 HTML 模板中为 *ngIf 使用枚举

c++ - 在这种情况下, 'addition' 和 'bitwise or' 是否相同?

javascript - 在嵌套 Promises 中使用时,来自外部作用域的数组被错误地报告为空