Dot Net developer
Dot Net developer

Reputation: 436

All Values replaced by last value in For loop TypeScript

I have a for loop in javascript which concats data in calendarEvents:

drop(info) {
    var that = this;
    var startDate = info.date;
    var frequency = this.skippingNumber;

    for (var i = 0; i <= 3; i++) {
      (function (start) {
        that.calendarEvents = that.calendarEvents.concat({
          title: 'Dropped Event',
          start: start,
          allDay: info.allDay
        });
      })(startDate);
      startDate = this.addDays(startDate, frequency);
    }
  }

addDays(date: Date, days: number): Date {
    var passedDate = date;
    passedDate.setDate(passedDate.getDate() + days);
    return passedDate;
  }

If I log startDate inside the loop , I get actual values i.e, Monday, Tuesday, Wednesday, Thursday. But when I log calendarEvents, all I get is Thursday in every data. Can anyone help me with this? Thanks in advance !!

Upvotes: 0

Views: 288

Answers (2)

Will Jenkins
Will Jenkins

Reputation: 9787

You only have one startdate object that you're mutating as the loop runs. When it finishes, you have an array that contains references to the same object.

One fix would be to clone your startdate object before you concat it into the array:

(function (start) {
    that.calendarEvents = that.calendarEvents.concat({
      title: 'Dropped Event',
      start: new Date(start.getTime()),
      allDay: info.allDay
    });
  })(startDate);

Though as suggested it would be better to re-write your addDays function so that it doesn't mutate the date object you pass in. Where possible, functions should not mutate their inputs.

Upvotes: 0

axiac
axiac

Reputation: 72226

All invocations of addDays() receive as argument, modify and return the same object (var startDate = info.date).

Rewrite the addDays() method to create and return a new Date object:

addDays(date: Date, days: number): Date {
    var passedDate = new Date(date.getTime());
    passedDate.setDate(passedDate.getDate() + days);
    return passedDate;
}

Upvotes: 3

Related Questions