Lukáš Frajt Lukáš Frajt - 3 months ago 9
TypeScript Question

Array of Date with for loop

I have problem with this code. If I print item of daysArray in for loop (console.log(daysArray[i]);) it returns right date, but after for loop returns last date at all daysArray items.
Please some could help me.

public getFullMonth(date: Date): Array<Date> {
var firstDay = this.getSunday(date);
var daysArray: Array<Date> = Array<Date>();

for (var i = 0; i < 43; i++) {
firstDay.setDate(firstDay.getDate() + 1);
daysArray[i] = firstDay;
console.log(daysArray[i]);
}

console.log(daysArray.length);
console.log(daysArray[0]);
console.log(daysArray[30]);
return daysArray;
}

Answer

The problem is that you always use the same instance of Date, you never create a new one, so all of the items in daysArray are the same exact instance.

Because of that, when you do:

firstDay.setDate(firstDay.getDate() + 1);

Then you actually change the value for all items.
You should create a new instance for every item:

public getFullMonth(date: Date): Array<Date> {
    var firstDay = this.getSunday(date);
    var daysArray: Array<Date> = Array<Date>();

    for (var i = 0; i < 43; i++) {
        firstDay = new Date(firstDay.getTime());
        firstDay.setDate(firstDay.getDate() + 1);
        daysArray[i] = firstDay;
        console.log(daysArray[i]);
    }

    console.log(daysArray.length);
    console.log(daysArray[0]);
    console.log(daysArray[30]);
    return daysArray;
}

Notice that each iteration now does:

firstDay = new Date(firstDay.getTime());

Which creates a new instance of Date which is a "clone" of the previous one.