我有一个 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);
}
在本例中,年份为2020年显示两次。我想要像2019年和2020年这样的东西。就像变量被多次引用一样。
每次迭代时都应创建一个新对象。您每次都引用相同的对象。
你可以这样做,
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,
});
}
或者喜欢,
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);
}
对象的引用被推送到数组中。而是克隆或创建副本,然后推送
const temp = {};
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)
Object.assign(temp, this.data);
this.dataSource.push(temp);
};
你可以
试试这个:-
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(Object.assign({}, this.data));
}