AmishJohn81 AmishJohn81 - 5 months ago 12
Node.js Question

Why is my array being overwritten?

I am using node.js for a project and I am trying to add certain dates to an array. However, when I do, it overwrites the entire array with the current date being added. Source below:

let startDate = new Date(2014, 0, 8, 19, 0, 0)
let endDate = new Date(2014, 0, 11, 19, 0, 0)
let datesToDownload = []
let datesInDB = [new Date(2014, 0, 8, 19, 0, 0), new Date(2014, 0, 9, 19, 0, 0), new Date(2014, 0, 10, 19, 0, 0), new Date(2014, 0, 8, 11, 0, 0)]

for (let i = startDate; i <= endDate; i.setDate(i.getDate() + 1)) {
console.log('CHECKING DATE: ' + i.toDateString())

if (!(datesInDB2.indexOf(i.toDateString()) >= 0)) {
console.log('NEW RECORD FOUND FOR: ' + i.toDateString())
datesToDownload.push(i)
console.log('i: ' + i)

for (let j in datesToDownload) {
console.log('element ' + j + ': ' + datesToDownload[j])
}
}
}


And the output looks like this:

CHECKING DATE: Wed Jan 08 2014
NEW RECORD FOUND FOR: Wed Jan 03 2014

i: Wed Jan 08 2016 20:00:00 GMT-0400 (Eastern Daylight Time)
element 0: Wed Jan 08 2016 20:00:00 GMT-0400 (Eastern Daylight Time)

CHECKING DATE: Thur Jan 09 2016
NEW RECORD FOUND FOR: Thur Jan 09 2016

i: Thur Jan 09 2016 20:00:00 GMT-0400 (Eastern Daylight Time)
element 0: Thur Jan 09 2016 20:00:00 GMT-0400 (Eastern Daylight Time)
element 1: Thur Jan 09 2016 20:00:00 GMT-0400 (Eastern Daylight Time)

CHECKING DATE: Fri Jan 10 2016
NEW RECORD FOUND FOR: Fri Jan 10 2016

i: Fri Jan 10 2016 20:00:00 GMT-0400 (Eastern Daylight Time)
element 0: Fri Jan 10 2016 20:00:00 GMT-0400 (Eastern Daylight Time)
element 1: Fri Jan 10 2016 20:00:00 GMT-0400 (Eastern Daylight Time)
element 2: Fri Jan 10 2016 20:00:00 GMT-0400 (Eastern Daylight Time)

......


Notice how the elements are all changed to the current date being inserted, though an element is being added.

Why is this happening? How can I prevent it?

Answer

You're pushing exactly the same Date instance into the array on each iteration. You can create a copy of it however:

  datesToDownload.push(new Date(i));