gpt4 book ai didi

javascript - 当从 `for` 循环内的 while 循环将值插入数组时,它会覆盖数组中的先前元素

转载 作者:太空宇宙 更新时间:2023-11-04 15:46:55 24 4
gpt4 key购买 nike

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com