我的Typescript类中有三个变量:
A:number;
B:number;
C:number;
在课程的另一部分中,我尝试添加两个变量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是olso数字类型,我已经找到了解决此问题的方法,但是打字脚本编译器输出错误(禁止使用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);
}
}
当您在接口中声明属性为a时number
,它仅保留为声明,不会将其翻译为javascript。
例如:
interface Response {
a: number;
b: number;
}
let jsonString = '{"a":"1","b":"2"}';
let response1 = JSON.parse(jsonString) as Response;
console.log(typeof response1.a); // string
console.log(typeof response1.b); // string
console.log(response1.a + response1.b); // 12
如您所见,json具有a
和b
作为字符串而不是数字,并且在接口中将它们声明为数字对运行时结果没有影响。
如果从服务器获取的内容被编码为字符串而不是数字,则需要对其进行转换,例如:
let response2 = {
a: Number(response1.a),
b: Number(response1.b)
} as Response;
console.log(typeof response2.a); // number
console.log(typeof response2.b); // number
console.log(response2.a + response2.b); // 3
(整个代码在操场上)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句