0

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;
}
2
  • What exactly you want ? and could you share fiddle for this ? Commented Sep 9, 2016 at 7:49
  • can you share your array of date values? Commented Sep 9, 2016 at 7:53

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

0

Your problem is easy to solve. You are just copying the same item in each position of the array. These means you are overriding the value you set in each step of the for loop.

Just create a new object for each position of the array and you won't have the error any more. Something like this

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.