gpt4 book ai didi

javascript - TypeScript Angular - 将字符串添加到数字属性会导致值为零 (0)

转载 作者:行者123 更新时间:2023-11-30 20:29:01 25 4
gpt4 key购买 nike

我正在使用 Angular 和 Typescript,我想知道如果我将一个字符串值(例如“hahah”)添加到一个应该只接受数字的字段并且它绑定(bind)到类型数字的属性也不会触发或触发任何错误,该字段的值将为零!我的意思是这对我来说很好,结果为零比结果为某个奇怪的值更好,但我很好奇这是怎么回事?

这是我的 typescript 类的样子:

export class Article {

public id: string;
public price: number;
public price2: number;

}

这是我的模板 .html 文件:

<div class="form-group">
<label class="control-label dash-control-label col-sm-3" for="">Price:</label>
<div class="col-sm-3">
<input type="text" class="form-control dash-form-control" id="" placeholder="" name="price" [(ngModel)]="article.price">
</div>

<label class="control-label dash-control-label col-sm-3" for="">Price 2:</label>
<div class="col-sm-3">
<input type="text" class="form-control dash-form-control" id="" placeholder="" name="price2" [(ngModel)]="article.price2">
</div>
</div>

正如你所看到的,输入绑定(bind)到 [(ngModel)]="article.price"[(ngModel)]="article.price2" 应用程序运行时它们看起来像这样:

enter image description here

但如果我输入如下内容,一切都很好:

enter image description here

当我发帖时,我的数据库中存储的值是:零 (0)!

怎么会?

为什么我尝试将字符串添加到数字或其他内容时没有出现错误?

谢谢

最佳答案

是啊!

Typescript changing the value depends by the property type without throwing error.

喜欢

add(a:number , bnumber )
{
console.log(a+b);
}

add("1",2);// result is 3

所以如果你传递字符串 add("aa"+"aa"); 它返回 0。因为函数参数 (number n,number n2) 是类型.所以它正在转换一个数字(如果它不是一个数字那么它假设为 0)


建议:

the better way is you can use type="number" instead of type="text" in your input element to avoiding to type any string value in the input box

<div class="form-group">
<label class="control-label dash-control-label col-sm-3" for="">Price:</label>
<div class="col-sm-3">
<input type="number" class="form-control dash-form-control" id="" placeholder="" name="price" [(ngModel)]="article.price">
</div>

<label class="control-label dash-control-label col-sm-3" for="">Price 2:</label>
<div class="col-sm-3">
<input type="number" class="form-control dash-form-control" id="" placeholder="" name="price2" [(ngModel)]="article.price2">
</div>
</div>

关于javascript - TypeScript Angular - 将字符串添加到数字属性会导致值为零 (0),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50567627/

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