This is the function (I feel I did the same thing a few hours ago and the output was what I was expecting)
function errorFunction() {
let master = []
let a = [1,2] //a simple array to loop over
a.forEach(function(b) {
let theDate = Date.today() // 8th Sep 2021
let i = 0
while (i<2) {
theDate = Date.parse(theDate).addDays(1)
Logger.log(theDate) // dates are alternating between 9th and 10th september
master.push([b,i,theDate])
i = i+1
}
})
Logger.log(master) // all dates are 10th september
}
The code is pushing 9th September and 10th September to the array. But the output of the array has only 10th September.
What I expect :
[
[1.0, 0.0, Fri Sep 9 00:00:00 GMT+05:30 2021],
[1.0, 1.0, Fri Sep 10 00:00:00 GMT+05:30 2021],
[2.0, 0.0, Fri Sep 9 00:00:00 GMT+05:30 2021],
[2.0, 1.0, Fri Sep 10 00:00:00 GMT+05:30 2021]
]
The Output I get :
[
[1.0, 0.0, Fri Sep 10 00:00:00 GMT+05:30 2021],
[1.0, 1.0, Fri Sep 10 00:00:00 GMT+05:30 2021],
[2.0, 0.0, Fri Sep 10 00:00:00 GMT+05:30 2021],
[2.0, 1.0, Fri Sep 10 00:00:00 GMT+05:30 2021]
]
I am using the latest version of DateJs library.
If you pass a
Dateobject to theparse()method of DateJS, it will return the object (link), and theaddDate()method also does not create a new object (link). So while you created a newtheDateobject for everybvalue, you modified the same object in thewhileloop, and put references to it into themasterarray.The solution is to create a new
Dateobject every time you modifytheDate. For example, change this line:...to this:
...or this (DateJS defines a
clone()method):This will clone the
theDateobject before adding 1 day to it.