Home > Blockchain >  Array Push method inside loop not displaying expected results
Array Push method inside loop not displaying expected results

Time:12-29

I have 2 dates. Date1 = "1/1/2022" and Date2 = "1/3/2022". I want to create an array consisting of ["1/1/2022", "1/2/2022", "1/3/2022"]. Quite straightforward. Not sure why my code is not working. Attached is screenshot image of my code after it runs. The array result it's giving me is ["1/4/2022", "1/4/2022", "1/4/2022"].

code and console.log

function test1() {
    var array = []
    var date1 = new Date(2022, 0, 1)
    var date2 = new Date(2022, 0, 3)
    d = date1
    while (d <= date2) {
        console.log(d)
        array.push(d)
        d.setDate(d.getDate()   1)
    }

    console.log(array)
}

test1();

CodePudding user response:

you are updating the same reference, which is changing values already stored in array.

try this:

while(d <= date2) {
   array.push(d)
   var copy = new Date()
   copy.setTime(d.getTime())
   copy.setDate(d.getDate()   1)
   d = copy
}

this will ensure that d is a new object in each iteration.

CodePudding user response:

Try this:

  function test1() {
    var array = [];
    var date1 = new Date(2022, 0, 1);
    var date2 = new Date(2022, 0, 3);
    d = date1;
    while (d.valueOf() <= date2.valueOf()) {
        console.log(d);
        array.push(new Date(d));
        d.setDate(d.getDate()   1);
    }
  console.log(array)    
  }

Execution log
5:49:29 PM  Notice  Execution started
5:49:29 PM  Info    Sat Jan 01 2022 00:00:00 GMT-0700 (Mountain Standard Time)
5:49:29 PM  Info    Sun Jan 02 2022 00:00:00 GMT-0700 (Mountain Standard Time)
5:49:29 PM  Info    Mon Jan 03 2022 00:00:00 GMT-0700 (Mountain Standard Time)
5:49:29 PM  Info    [ Sat Jan 01 2022 00:00:00 GMT-0700 (Mountain Standard Time),
  Sun Jan 02 2022 00:00:00 GMT-0700 (Mountain Standard Time),
  Mon Jan 03 2022 00:00:00 GMT-0700 (Mountain Standard Time) ]
5:49:30 PM  Notice  Execution completed
  • Related