gpt4 book ai didi

javascript - '+' 在 AngularJS 中执行连接而不是加法

转载 作者:行者123 更新时间:2023-12-01 03:28:11 24 4
gpt4 key购买 nike

这是我在 TypeScript 中实现一个简单计算器的代码。这里的问题是,除了加法之外,所有操作都工作正常,其中执行的不是加法,而是数字的串联。

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>

我的 Angular 代码如下:

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() {

}

}

我已将 n1n2 声明为数字,并将结果声明为数字。那么为什么数字被视为字符串而不是整数呢?

注意:我已经浏览了其他一些有关类似问题的 Stack Overflow 帖子,但找不到可能的解决方案。

请帮忙!

最佳答案

你可以解决它。 this.结果=(+this.n1)+(+this.n2);

关于javascript - '+' 在 AngularJS 中执行连接而不是加法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44681070/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com