我有这个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的东西。就像变量被多次引用一样。
答案 0 :(得分:4)
应该在每次迭代中创建一个新对象。每次都指向同一对象。
您可以这样做
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);
}
答案 1 :(得分:1)
对象的引用被推入数组。而是克隆或创建副本,然后按
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);
};
答案 2 :(得分:0)
您可以尝试以下操作:-
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));
}