Reputation: 1
this is totally new for me, if I assign a date to a array record, seems ok, but if I'm assigning the next day to the next record, the system is changing also the first :O :O :O and so on...
I can't post images, but just try to debug...
function myFunction() {
var test=[];
var startDate = new Date(2014,11, 01); //01 dic 2014
var nextDate = startDate ;
for (i=0; i<=10; i++){
test.push(nextDate);
nextDate.setDate(nextDate.getDate()+1);
}
Upvotes: 0
Views: 32
Reputation: 46812
You are pushing the same date object all the time. Try like below :
function myFunction() {
var test=[];
var startDate = new Date(2014,11, 01); //01 dic 2014
var nextDate = startDate ;
for (i=0; i<=10; i++){
var newDate = new Date(nextDate.setDate(nextDate.getDate()+1));
test.push(newDate);
}
Logger.log(JSON.stringify(test));
}
EDIT :
To make things more clear and to show the the nextDate
variable is still the same all along the script execution , here is an example that shows what happens in your original code. I logged the values of nextDate
in the loop then logged the resulting array. You can indeed see that all values are identical in the array while they change in the loop (and values in the array are the last value in the loop).
Now let's change nextDate
again and re-check the array, all the values are changed again, that's actually because we have a one and only object.
bad code below :
function myFunction2() {
var test=[];
var startDate = new Date(2014,11, 01); //01 dic 2014
var nextDate = startDate ;
for (i=0; i<=10; i++){
test.push(nextDate);
Logger.log(nextDate);
nextDate.setDate(nextDate.getDate()+1);
}
Logger.log(test);
nextDate.setDate(0);
Logger.log(test);
}
result in logger :
Upvotes: 1