“+”被执行,而不是另外在AngularJS
这里拼接是我的代码中,我在打字稿。问题实现一个简单的计算器这里,所有的操作,不同的是另外的地方而不是另外做工精细,数字的级联执行。“+”被执行,而不是另外在AngularJS
HTML代码:
<input type="text" [(ngModel)]="n1" />
<input type="text" [(ngModel)]="n2" />
<h1>Number 1 : {{n1}}</h1>
<h1>Number 2 : {{n2}}</h1>
<select (change)="handle(selectField.value);" #selectField>
<option value="addition">Addition</option>
<option value="subtraction">Subtraction</option>
<option value="multiply">Multiplication</option>
<option value="divide">Division</option>
</select>
<h1>Result = {{result}}</h1>
我的角度代码如下:
import {
Component,
OnInit
} from '@angular/core';
@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {
n1: number = 0;
n2: number = 0;
result: number = 0;
handle(value: string) {
if (value == "addition") {
this.result = this.n1 + this.n2;
} else if (value == "subtraction") {
this.result = this.n1 - this.n2;
} else if (value == "multiply") {
this.result = this.n1 * this.n2;
} else if (value == "divide") {
this.result = this.n1/this.n2;
}
}
constructor() {}
ngOnInit() {
}
}
我宣布双方n1
和n2
数字和也的结果作为数字。那么为什么这些数字被视为字符串而不是整数?
注:我已经经历了类似的问题,其他一些堆栈溢出的职位走了,但没有找到可行的解决方案。
请帮忙!
你可以解决它。 this.result =(+ this.n1)+(+ this.n2);
虽然这个代码片断可以解决问题,[包括解释](// meta.stackexchange.com/questions/114762/explaining-entirely-code-based-answers)确实有助于提高您的帖子的质量。请记住,您将来会为读者回答问题,而这些人可能不知道您的代码建议的原因。也请尽量不要用解释性注释来挤占代码,这会降低代码和解释的可读性! –
从HTML输入任何值自动是字符串。要解决此问题,您必须将您的输入值转换/转换为数字。 (+ this.n1)破解它,但要真正做到这一点,你应该施放或转换你的值。
this.result = parseInt(this.n1) + parseInt(this.n2);
这只是一种方式。还有其他几个。
我还应该注意,如果输入的值计算为NAN,则此方法很容易失败。 – MBielski
,因为它们都是字符串他们被视为字符串。我假设你将UI中的一些元素绑定到'n1'和'n2'? – Amy
请注意,TypeScript只执行编译时类型检查,而不是运行时。 –
您可以解决它。 this.result =(+ this.n1)+(+ this.n2); – aimprogman