在Angular 5中输出两个数字的NaN

时间:2018-05-28 08:00:21

标签: angular typescript

我试图将两个数字相乘并添加另一个数字,但输出显示为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
}

3 个答案:

答案 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
}