2

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

2 Answers 2

6
...
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

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the explanation. Makes perfect sense and hopefully something I'll learn from!
2

function sevenDayPeriod(date) {
    for (var i = 0; i <=6; i++) {
	//date object is as a "pointer", you have to clone it
	var copiedDate = new Date(date);
		
        //alert(date); //check to see date is today's date
        dateRange[i] = copiedDate;
        //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);

console.log(dateRange);

When you modify the date, you are you're also changing pushed date. You have to clone it.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.