0

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.

Igor Artamonov
  • 35,450
  • 10
  • 82
  • 113

1 Answers1

0

In Javascript, objects are not copied when assigned. They are assigned by reference.

In your Request() constructor, this line of code:

this.date = date

is not making a copy of the date parameter, it's just point this.date at the passed in orderDate object. When that orderDate object changes in the future, this.date will be pointing at the changed object. So, as you then change that orderDate object in your loop, every Request object ends up pointing at the same orderDate object so they all see the value at the end of the loop.

You can fix your code by doing this:

this.date = new Date(date);

This will make a copy of the passed-in date object.

jfriend00
  • 683,504
  • 96
  • 985
  • 979
  • Brilliant. Thank you. And it was something so simple, that has actually taught me an incredibly important lesson about how JavaScript works. – Chris Wheatland Jun 16 '16 at 12:54