I'm reasonably new to coding so this might be a silly question but, I'm trying to use a for loop to create multiple instances of an object, each of which takes a date incremented by one day. My problem is that every instance of the object ends up taking the same date value: that of the final iteration. I did some searching and one answer seemed to be that the variable I was using to keep track of the date is static. I don't know if that's my problem or indeed how to solve it so any help would be much appreciated.
//getMonday is a function that returns the first day of the week from a given d
var TestObject = function(date) {
this.date = date;
}
function dateTest() {
var today = new Date();
var contents = [];
var orderDate = new Date(getMonday(today));
var j = 0;
for(var k = 1; k<6; k++) {
for(var i = 0; i<6; i++) {
contents[j] = new TestObject(orderDate);
Logger.log("filling in contents[" + j + "]. I'm putting in date: " + orderDate);
j++;
}
orderDate.setDate(orderDate.getDate() + 1);
}
for(var i = 0; i < contents.length; i++) {
Logger.log(contents[i]);
}
}
There are two loops because I need to loop twice in my particular instance of the code, it strips values out of a spreadhseet and only increments the date when the row number changes.
The Log inside the for loop prints out all the correct dates, but when the dateTest objects are all printed out they all contain the final date iteration.