【问题标题】:When pushing values into an array from a while loop that is inside a `for` loop, it overwrites the previous elements in the array当从 for 循环内的 while 循环中将值推入数组时,它会覆盖数组中的先前元素
【发布时间】:2017-09-15 19:30:25
【问题描述】:

当我将值从 for 循环中的 while 循环推入数组时,它会覆盖数组中的先前元素。

        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);
        }

【问题讨论】:

    标签: javascript arrays date for-loop while-loop


    【解决方案1】:

    当我在 for 循环内的 while 循环内推送值时,它会覆盖 数组中的前一个元素。

    因为您每次都在更新同一个对象并将其推送到数组中,

    改变这一行

    nextDate = this.sumDays(nextDate , OldCycle);
    

    nextDate = new Date(this.sumDays(nextDate , OldCycle).getTime());
    

    这将每次创建一个新的 Date 对象。

    【讨论】:

    • @LaiaChorroYanguas 请点赞并接受对您有帮助的正确答案meta.stackexchange.com/questions/5234/…
    • 我现在注意到我的数组的最后一个值总是重复的,为什么会这样?
    • @LaiaChorroYanguas 您也需要在 while 循环之外执行此操作
    • 我认为这会解决它!
    • @gurvinder372 我在代码中的任何地方都应用了这个,但不知道为什么在数组末尾复制了一些元素。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-25
    相关资源
    最近更新 更多