我试图将两个数字相乘并添加另一个数字,但输出显示为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
}
答案 0 :(得分:2)
应该是这样的:
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>();
答案 1 :(得分:1)
this.sum = this.sum + +this.medicines[i].price * +this.medicines[i].quantity;
将+
放在属性之前,因此如果它不是数字,它会将您的属性值转换为数字。
答案 2 :(得分:0)
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
}