我正在构建一个租金计算器应用程序,它有3个字段--总租金、年租金增量和计算.when租金的年数--我在输入字段中填写了输入字段,代码只打印第一次迭代多次,我想要它打印随年数增加的值。
Html文件
租金计算器
<input type="number" name="rent" placeholder="Enter your total rent" [(ngModel)]="rent" />
<input type="number" placeholder="Rent increase per Year" [(ngModel)]="increase">
<input type="number" placeholder="Number of Total Years" [(ngModel)]="months">
<button type="button" (click)="calculate()"> Calculate </button>
<br>
<h4 *ngFor="let r of total;let i=index">
Year {{i+1}} = {{r}} Rs
</h4>
ts文件..。
export class RentCalculatorComponent {
constructor() { }
increase!: number;
months!: number;
rent!: number;
new!: number;
total: any[] = [];//declare an array
calculate() {
for (let i = 0; i <= this.months - 1; i++) {
this.new = this.rent + this.rent * this.increase / 100;
this.total[i] = this.new.toFixed(2);; //here store in the array the result
console.log(this.total[i]);
}
}
}
发布于 2022-09-23 11:25:09
您正在初始化长度为0的数组。当您从0循环到month.length - 1
时,基本上是将值设置在数组的界限之外。您应该尝试使用this.total.push(this.new.toFixed(2));
来增加数组的长度。
尽管如此,还是有几个暗示:
new
,因为在许多语言)。
https://stackoverflow.com/questions/73826272
复制相似问题