我正在尝试将两个数字相乘并添加另一个数字,但输出显示为 NaN。如何解决这个问题?
这是我的代码
medicines = [new Medicine()];
this.sum = 0;// sum also type of number
for (let i = 0; i < this.medicines.length; i++)
{
this.sum = this.sum + this.medicines[i].price * this.medicines[i].quantity;//here price and quantity of type number
console.log(typeof this.sum);//but this print NaN
}
药品模型
export class Medicine{
constructor(){}
name: String;
quantity:number;
price:number
}
它应该是这样的:
medicines:Medicine[]=[{name: 'name', quantity:3, price:6},{name: 'name', quantity:3, price:6},{name: 'name', quantity:3, price:6}]
或:
medicines: Array<Medicine> = new Array<Medicine>();
你能这样做吗
this.sum = this.sum + +this.medicines[i].price * +this.medicines[i].quantity;
将+
放在属性之前,因此如果不是数字,它会将您的属性值转换为数字。
medicines: [] = new Medicine();
this.sum = 0;// sum also type of number
for (let i = 0; i < this.medicines.length; i++)
{
this.sum = this.sum + this.medicines[i].price * this.medicines[i].quantity;//here price and quantity of type number
console.log(typeof this.sum);//but this print NaN
}