I’m trying to populate an array with a list of dates.
When I go back to retrieve a date in the array, they are all the same date.
var paydates = new Array();
var i;
var firstDate = new Date();
firstDate.setFullYear(2010, 11, 26); //set the first day in our array as 12/26/10
for (i=0; i < 200; i++) //put 200 dates in our array
{
paydates[i] = firstDate;
firstDate.setDate(firstDate.getDate()+14); //add 14 days
document.write("1st: " + i + ":" + paydates[i] + "<br />");
//this lists the dates correctly
}
//when I go back to retrieve them:
for (i=0; i < 200; i++)
{
document.write("2nd: " + i + ":" + paydates[i] + "<br />");
//this lists 200 instances of the same date
}
It’s probably something stupid, but I’m at a loss.
Thanks
In your loop, you assign
paydates[i]a reference tofirstDate. At the end of 200 iterations, all 200 locations in thepaydatesarray are pointing to the lastfirstDate.You should create a new
Dateinstance in each iteration and then assign it to an index in thepaydatesarray.Also, you’ll notice that the first date listed in your example is not 12/26/2010, but 1/9/2011. I’m not sure if that’s a mistake or intentional, but as your code is, the first
firstDateisn’t the date you used to seed your array of dates.JSFiddle of a working example that also simplifies your code a little bit. Here is the barebones code from the fiddle: