用日期填充数组

Fill an array with dates

真的不明白为什么我推入数组的日期不是我在控制台调用数组时出现的日期。即我希望数组中的第一个条目是今天的日期,这是两个警报调用返回的日期,但是当我检查数组的第一个位置时,它有昨天的日期!?

function sevenDayPeriod(date) {

    for (var i = 0; i <=6; i++) {

        alert(date);    //check to see date is today's date
        dateRange[i] = date;
        alert(dateRange[i]);    //confirm that what I've pushed to array is today's date

        date = date.setDate(date.getDate() - 1);
        date = new Date(date);
    }
};

var dateRange = [];
var today  = new Date();

sevenDayPeriod(today);

谢谢

...
dateRange[i] = date;
alert(dateRange[i]);    //confirm that what I've pushed to array is today's date
date = date.setDate(date.getDate() - 1);
...

在上面的第一行中,您将第 i 个数组元素设置为 date(参考),然后显示它,然后用 setDate 更改同一对象,这会导致您问题,因为数组元素仍然指向修改后的对象。
你可以解决这个问题,例如像这样的另一个 var

...
var prevDay = new Date();
prevDay.setDate(date.getDate() - 1);
date = prevDay;
...  

或者在将其推入数组之前创建它的副本

function sevenDayPeriod(date) {
    for (var i = 0; i <=6; i++) {
 //date object is as a "pointer", you have to clone it
 var copiedDate = new Date(date);
  
        //alert(date); //check to see date is today's date
        dateRange[i] = copiedDate;
        //alert(dateRange[i]); //confirm that what I've pushed to array is today's date
  
        date = date.setDate(date.getDate() - 1);
        date = new Date(date);
    }
};

var dateRange = [];
var today  = new Date();

sevenDayPeriod(today);

console.log(dateRange);

当您修改日期时,您也在更改推送日期。你必须克隆它。