Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
147
rated 0 times [  153] [ 6]  / answers: 1 / hits: 25162  / 10 Years ago, sun, january 18, 2015, 12:00:00

I'm using Moment.js to make a Resource Calendar and I need an array of dates for this week. The console log of my current function prints out appropriately but the array that gets pushed in for each date is wrong.



    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)]


Notice how the array at the bottom is the next date in the array repeated 7 times.


More From » arrays

 Answers
70

As danludwig mentioned in his comment on the question, you are adding a reference for the same date to the array multiple times.


From the 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.



You should be calling the clone function on the Moment date object as shown 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);

As an aside:


You should not reference internal fields/functions of a 3rd party library. The name of these references are more likely to change than the public API described in the documentation. _d can be referenced by calling the public function toDate.


[#68171] Thursday, January 15, 2015, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
byronkodyo

Total Points: 552
Total Questions: 87
Total Answers: 104

Location: Burundi
Member since Sat, Aug 21, 2021
3 Years ago
;