0

Sorry I'm a beginner and I'm really stuck. I want the following code to PUSH the following dates for me into an array: Jan 01 2017 Mar 31 2017 Apr 01 2017 Jun 30 2017 Jul 01 2017 Sep 30 2017 Oct 01 2017 Dec 31 2017

... etc. Which is correctly coming out of the console.log(s). That's why I'm trying use dates.push(s) to save them in an array. However, it's saving incorrectly; when I print dates[], the array is filled only with "January 1 2022". I can't figure out why


    var s = startDate;
var dates = [];

while (s < today) {
    console.log(s);
    dates.push(s);
 
    s.setMonth(s.getMonth() + 3);
    s.setDate(s.getDate() - 1);

    dates.push(s);
    
    console.log(s);
    
    s.setDate(s.getDate() + 1);
    

}


dates.forEach(function(dates) {
  console.log(dates);

  //this just returns January 1, 2022 over and over
});

Thank you so much for your help!

deathloser
  • 31
  • 5
  • Clarifying: startDate = January 1 2017 – deathloser Dec 21 '21 at 14:41
  • 2
    There's only one "date" -> `s`. Your script pushes references to that one "date" into `dates` ([Is JavaScript a pass-by-reference or pass-by-value language?](https://stackoverflow.com/questions/518000/is-javascript-a-pass-by-reference-or-pass-by-value-language)). In the end you will have a bunch of pointers (references) that all point to that one "date" – Andreas Dec 21 '21 at 14:44
  • Thank you! It's hard to understand but very important – deathloser Dec 21 '21 at 17:43
  • You need a new `Date` instance in every round of the `while` loop – Andreas Dec 21 '21 at 17:51
  • Or you can push strings: `dates.push(s.toString());`. :-) – RobG Dec 22 '21 at 03:05

0 Answers0