使用 Moment.js 制作本周日期的数组不会添加到数组中

Using Moment.js to make an array of this week's dates doesn't add to array

我正在使用 Moment.js 制作资源日历,我需要一组本周的日期。我当前函数的控制台日志正确打印​​出来,但是为每个日期推送的数组是错误的。

    var startOfWeek = moment().startOf('week');
    var endOfWeek = moment().endOf('week');

    var days = [];
    var day = startOfWeek;

    do {
        console.log(day._d);
        days.push(day._d);
        day = day.add(1, 'd');
    }
    while (day <= endOfWeek);

    console.log(days);

Returns:

Sun Jan 18 2015 00:00:00 GMT-0500 (EST) schedule.js?320233fd69f9859ccb55248b608e15891032b17d:31
Mon Jan 19 2015 00:00:00 GMT-0500 (EST) schedule.js?320233fd69f9859ccb55248b608e15891032b17d:31
Tue Jan 20 2015 00:00:00 GMT-0500 (EST) schedule.js?320233fd69f9859ccb55248b608e15891032b17d:31
Wed Jan 21 2015 00:00:00 GMT-0500 (EST) schedule.js?320233fd69f9859ccb55248b608e15891032b17d:31
Thu Jan 22 2015 00:00:00 GMT-0500 (EST) schedule.js?320233fd69f9859ccb55248b608e15891032b17d:31
Fri Jan 23 2015 00:00:00 GMT-0500 (EST) schedule.js?320233fd69f9859ccb55248b608e15891032b17d:31
Sat Jan 24 2015 00:00:00 GMT-0500 (EST) schedule.js?320233fd69f9859ccb55248b608e15891032b17d:31
[Sun Jan 25 2015 00:00:00 GMT-0500 (EST), Sun Jan 25 2015 00:00:00 GMT-0500 (EST), Sun Jan 25 2015 00:00:00 GMT-0500 (EST), Sun Jan 25 2015 00:00:00 GMT-0500 (EST), Sun Jan 25 2015 00:00:00 GMT-0500 (EST), Sun Jan 25 2015 00:00:00 GMT-0500 (EST), Sun Jan 25 2015 00:00:00 GMT-0500 (EST)]

注意底部的数组是数组中重复 7 次的下一个日期。

正如 danludwig 在他对问题的评论中提到的,您多次向数组添加同一日期的引用。

来自Moment.js documentation

It should be noted that moments are mutable. Calling any of the manipulation methods will change the original moment.

If you want to create a copy and manipulate it, you should use moment#clone before manipulating the moment.

您应该在 Moment 日期对象上调用 clone 函数,如图 here

var startOfWeek = moment().startOf('week');
var endOfWeek = moment().endOf('week');

var days = [];
var day = startOfWeek;

while (day <= endOfWeek) {
    days.push(day.toDate());
    day = day.clone().add(1, 'd');
}

console.log(days);

顺便说一句:

不应该 引用第 3 方库的内部 fields/functions。这些引用的名称比文档中描述的 public API 更有可能发生变化。 _d可以通过调用public functiontoDate.

来引用