简体   繁体   English

For循环仅多次打印第一次迭代

[英]For loop only printing first iteration multiple time

I am building a rent calculator app which have 3 fields total rent,rent incresese per year and number of years to calculate rent for.when i fill the input field the code only print first iteration multiple time i want it to print increased value with years我正在构建一个租金计算器应用程序,它有 3 个字段的总租金、每年的租金增加和计算租金的年数。当我填写输入字段时,代码只打印第一次迭代多次我希望它打印增加的值与年

Html file Html 文件

Rent Calculator租金计算器

<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}}&nbsp; &nbsp;=&nbsp;&nbsp;{{r}}&nbsp;Rs

</h4>

ts file... 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]);

    }
  }
}

You are initializing an array of length 0. When you are looping from 0 to month.length - 1 you are basically setting values out of bounds of your array.您正在初始化一个长度为 0 的数组。当您从 0 循环到month.length - 1时,您基本上是在设置超出数组范围的值。 You should try to use this.total.push(this.new.toFixed(2));您应该尝试使用this.total.push(this.new.toFixed(2)); to increase the length of your array.增加数组的长度。

Nevertheless a couple of hints:不过有几个提示:

  • You should not name variables new , since this is a reserved word in many languages您不应将变量命名为new ,因为这是许多语言中的保留字
  • you should not use the "bang-operator" (or "non-null-assertion-operator") when the variable is indeed not set.当变量确实没有设置时,你不应该使用“bang-operator”(或“non-null-assertion-operator”)。 You should just initialize it with a valid value in your case您应该在您的情况下使用有效值对其进行初始化

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM