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

标签 javascript arrays date for-loop while-loop

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/

相关文章:

javascript - setInterval 这是获取通知的正确方法吗?

javascript - 滚动到 ASP.NET 列表框中第一个选定的项目

javascript - 格式化表头和表体

java - 如何在java中创建bitset类对象数组?

javascript - 将表解析为正则表达式方法

JavaScript:如何获取指定时区的日期时间

date - 比较 LocalDate 与 apache ignite 中 LocalDateTime 的日期部分

php - 如何在没有提交按钮的情况下提交选定的值?

javascript - 循环保存到 MongoDB

mysql - 每分钟给出日期,每两提取一次