MrProgram
MrProgram

Reputation: 5242

Fill array with months using loop

function dateColumn() {
    var startDate = new Date($("#anStartDate").val()); //the start date
    var pmtPeriods = $("#anPaymentPeriods").val(); //number of months in this case
    var dateData = new Array(pmtPeriods);
    var i = 0;
    while (i < pmtPeriods) {
        startDate = startDate.add(i).month();
        dateData[i] = startDate;
        i++
    }
    alert(dateData);
}

Let's say my start date is 2014-01-01 and I put 2 months as pmtPeriods. That fills my array with [2014-02-01, 2014-02-01]. If I take pmtPeriods as 3 with same start date result is [2014-03-01, 2014-03-01, 2014-03-01]. This is wrong.

With pmtPeriods 2 I would like result:

[2014-02-01, 2014-03-01]

instead of

[2014-02-01, 2014-02-01]

Upvotes: 0

Views: 266

Answers (1)

bmceldowney
bmceldowney

Reputation: 2305

You're adding startDate to the dateData array 3 times. That's just adding a reference to the startDate value which is getting updated in your loop. Change:

dateData[i] = startDate;

to

dateData[i] = new Date(startDate);

Upvotes: 3

Related Questions