I have a start date and an end date, and I want to generate a list of dates between (and including) these two dates. But I don\'t get why it isn\'t working...
I pass in
Because the same object is modified all elements referencing the same object
Try to add new Date(i)
, instead of just i
:
function dateList(dateStart, dateEnd) {
var dates = [];
for (i = dateStart; i <= dateEnd; i.setDate(i.getDate() + 1)){
dates.push(new Date(i));
}
return dates;
}
console.log(dateList(new Date('2017-05-08'), new Date('2017-05-12')));
Your code i.setDate(i.getDate() + 1)
doesn't create a new date - it just updates the same Date object over and over. Then you push that object onto the array, which pushes a reference to that object - not a copy of the object.
A solution would be to create a new Date()
inside the loop and setting the value of it, and then pushing this new date onto your array.