Search code examples
javascriptarraysbyref

Fill an array with dates


Really can't see why the dates I'm pushing into an array are not the dates that come out when I call the array in the console. i.e. I would expect the first entry in the array to be today's date, which is what comes back from both alert calls, but when I check the array's first position it has yesterday's date instead!?

function sevenDayPeriod(date) {

    for (var i = 0; i <=6; i++) {

        alert(date);    //check to see date is today's date
        dateRange[i] = date;
        alert(dateRange[i]);    //confirm that what I've pushed to array is today's date

        date = date.setDate(date.getDate() - 1);
        date = new Date(date);
    }
};

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

sevenDayPeriod(today);

Thanks


Solution

  • ...
    dateRange[i] = date;
    alert(dateRange[i]);    //confirm that what I've pushed to array is today's date
    date = date.setDate(date.getDate() - 1);
    ...
    

    In the first of the above lines you set the ith array element to date (a reference), then you show it and afterwards you change the same object with setDate which results in your problem, as the array element still points to that modified object.
    You can solve that e.g. with another var like so

    ...
    var prevDay = new Date();
    prevDay.setDate(date.getDate() - 1);
    date = prevDay;
    ...  
    

    or create a copy of it prior to pushing it into the array