为什么我的数组中的所有Date元素都是相同的日期

Why are all Date elements in my array the same date?

本文关键字:日期 元素 数组 我的 为什么 Date      更新时间:2023-09-26

我对Javascript有一个非常奇怪的问题。我正试图循环我的日期,以进行一些检查并为数组添加值,但当我返回数组时,它会显示我的所有集合和最后一个值。以下是我的代码:

function myFunction() {
    var todayDate = new Date();
    var firstDay = new Date(todayDate.getFullYear(), todayDate.getMonth(), 1);
    var lastDay = new Date(todayDate.getFullYear(), todayDate.getMonth() + 1, 0);
    var testDates=[];
        while (firstDay <= lastDay) {
            var currentDate = firstDay;
            testDates.push( firstDay);
            firstDay.setDate(firstDay.getDate() + 1);
        }
    document.getElementById("demo").innerHTML = testDates;
}

这是我所有日期的最后一个值:

2016年1月1日(星期五)00:00:002016年1月1日,星期五00:00:002016年00:00:00

为什么会发生这种情况?

您不是在数组中添加日期,而是对日期的引用。然后,如果更新firstDay,则更新数组中所有元素的日期。(因为它们都指向同一个日期)。尝试这样克隆日期:

function myFunction() {
    var todayDate = new Date();
    var firstDay = new Date(todayDate.getFullYear(), todayDate.getMonth(), 1);
    var lastDay = new Date(todayDate.getFullYear(), todayDate.getMonth() + 1, 0);
    var testDates=[];
    while (firstDay <= lastDay) {
        var currentDate = firstDay;
        testDates.push( new Date(firstDay.getTime()) );
        firstDay.setDate(firstDay.getDate() + 1);
    }
    document.getElementById("demo").innerHTML = testDates;
}

对这个注释做一点更改:为什么我的数组中的所有Date元素都是相同的日期?

function myFunction() {
    // Using variables definition pattern
    var todayDate = new Date(),
        firstDay = new Date(todayDate.getFullYear(), todayDate.getMonth(), 1),
        lastDay = new Date(todayDate.getFullYear(), todayDate.getMonth() + 1, 0),
        currentDate = firstDay,
        testDates=[];
    // Change firstDay to currentDate in comparison part of the loop
    while (currentDate <= lastDay) {
        testDates.push( new Date(currentDate.getTime()) );
        // Also change firstDay to currentDate because it's a temporary
        // variable used to perform calculations and moving through
        // values
        currentDate.setDate(currentDate.getDate() + 1);
    }
    document.getElementById("demo").innerHTML = testDates;
}

1) 变量定义模式允许您以更容易阅读代码的方式对变量的定义进行分组(请参阅中的);2) 在原始代码中这一行var currentDate=第一天;什么也不做,只是声明一个不在任何地方使用的变量。更改firstDay值也有点不正确,因为它来自变量名,所以不应该更改。我相信currentDate被认为是临时的,只是注意到了这一点。