0

I'm trying to create an array of date objects starting from a certain date up till today.

Here's the code I have:

var beginning = new Date("04,06,2013");

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

while (beginning < today){
    var x = beginning; 
    console.log(x);
    dates.push(x);
    beginning.setDate(beginning.getDate()+1)
}

for (var i in dates) {
  console.log(dates[i]);
}

In the while loop I see the correct dates incrementing but when I print out the dates in the array at the last for loop I see all the dates that are pushed being today's date.

Any ideas?

2 Answers2

1

What your code does is push a whole bunch of references to the exact same Date object. So, you have an array full of all the same Date object and each time you change that object, all elements in the array just point to the same object so they will all appear to change.

When you push an object into an array or assign an object to a variable, it does not make a copy, it pushes a reference to it (think of it like a pointer in other languages). To push different date objects for each iteration of the loop, you'd have to create a new date object each time through the loop and push that.

In javascript, assigning an object or an array to any variable (which includes pushing it into an array) only assigns a reference to that object or array, not a copy. This is a common issue that bits most people coming up to speed on javascript.

You can make a new date object each time through the loop like this:

var beginning = new Date("04,06,2013");

var dates = [];
var today = new Date(), x;

while (beginning < today){
    x = new Date(beginning.getTime()); 
    console.log(x);
    dates.push(x);
    beginning.setDate(beginning.getDate()+1)
}
jfriend00
  • 683,504
  • 96
  • 985
  • 979
0

You're only working with one single Date instance throughout all that code.

To create a copy of a Date, do this:

x = new Date(beginning.getTime());

Then call the .setDate() method to move it forward.

The setters on JavaScript Date instances change the object. They don't create a new one.

Pointy
  • 405,095
  • 59
  • 585
  • 614