When I push values into an array from a while loop inside that's for loop it overwrites the previous elements inside the array.
var startDate = new Date(theoreticalData[0].UpdateDateMDY);
var newDate = startDate;
var daysDif = 0;
var daysArray = [startDate];
for ( var i= 1; i<theoreticalData.length; i++ ) {
var OldCycle = parseInt(theoreticalData[i].OldCycle);
daysDif = theoreticalData[i].DaysDifference;
while (daysDif > OldCycle ) {
nextDate = this.sumDays(nextDate , OldCycle);
daysArray.push(nextDate);
daysDif = daysDif - OldCycle;
}
nextDate = this.sumDays(nextDate , daysDif);
daysArray.push(nextDate);
}
最佳答案
When I push values inside a while loop inside a for loop it overwrites the previous elements inside the array.
因为您每次都更新相同的对象并将其推送到数组,
更改此行
nextDate = this.sumDays(nextDate , OldCycle);
至
nextDate = new Date(this.sumDays(nextDate , OldCycle).getTime());
这将每次创建一个新的Date对象。
关于javascript - 当从 `for` 循环内的 while 循环将值插入数组时,它会覆盖数组中的先前元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43497925/