Javascript我的数组推仅获得最后一个值

use*_*830 0 javascript reactjs angular

我有这个for循环,我想在每个循环中增加年份,但是我只得到最后一年,它们都重复多次。

for (let i = 0; i < 2; i++) {
  this.data.year = new Date().getFullYear() + i;
  this.data.noSolar = averageBill * increaseRate;
  this.data.withSolar = (contractAmount * .004) + customerCharge;
  this.data.saving = (contractAmount * .004 + customerCharge) * 12 - (averageBill * 12);
  this.data.check = SREC;
  this.data.total = (contractAmount * .004 + customerCharge) * 12 - (averageBill * 12) + SREC;

  this.dataSource.push(this.data);
}
Run Code Online (Sandbox Code Playgroud)

在这种情况下,“ 2020年”显示了两次。我想要像2019和2020这样的东西。就像变量多次被引用一样。

Har*_*ary 6

每次迭代都应创建一个新对象。您每次都引用相同的对象。

你可以这样

for (let i = 0; i < 2; i++) {
  this.dataSource.push({
     year : new Date().getFullYear() + i,
     noSolar : averageBill * increaseRate,
     withSolar : (contractAmount * .004) + customerCharge,
     saving : (contractAmount * .004 + customerCharge) * 12 - (averageBill * 12),
     check : SREC,
     total : (contractAmount * .004 + customerCharge) * 12 - (averageBill * 12) + SREC,
  });
}
Run Code Online (Sandbox Code Playgroud)

或喜欢

for (let i = 0; i < 2; i++) {
      this.data=new DataSourceObject();
      this.data.year = new Date().getFullYear() + i;
      this.data.noSolar = averageBill * increaseRate;
      this.data.withSolar = (contractAmount * .004) + customerCharge;
      this.data.saving = (contractAmount * .004 + customerCharge) * 12 - (averageBill * 12);
      this.data.check = SREC;
      this.data.total = (contractAmount * .004 + customerCharge) * 12 - (averageBill * 12) + SREC;

      this.dataSource.push(this.data);
    }
Run Code Online (Sandbox Code Playgroud)