i'm working on a code that increments a date of an object in a while statement and put in an array at every iteration, i can't understand why but when i print the array on the console, the incremented date is alwais on the last day incremented, the code is here:
while (Difference_In_Days > 1) {
var assTemp = new assenza()
Difference_In_Days = date2.getDate() - date1.getDate();
assTemp.data_ass = date1
assTemp.id_ass = 0
assTemp.motivo = "" motivo
assTemp.dipendente = this.dipendente
this.assArr.push(assTemp)
var assTemp = new assenza()
date1.setDate(date1.getDate() 1)
}
and the result of the console.log(JSON.stringify(this.assArr)):
[ { "id_ass":0, "data_ass":"2021-10-15T00:00:00.000Z", "motivo":"salute", "dipendente":{} },
{ "id_ass":0, "data_ass":"2021-10-15T00:00:00.000Z", "motivo":"salute", "dipendente":{} },
{ "id_ass":0, "data_ass":"2021-10-15T00:00:00.000Z", "motivo":"salute", "dipendente":{} } ]
as you can see the data_ass(the dates) are always the same, why? if i put a console.log of date1 in the while it shows me a correct increment day by day trough the iterations. thanks for your help
CodePudding user response:
You simply need to copy date1 to assTemp.data_ass, rather than assigning the reference, by changing the line
assTemp.data_ass = date1
to
assTemp.data_ass = new Date(date1);
Otherwise each instance of assTemp will hold the same value for data_ass, namely the last value.