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);
}
假设我的开始日期是 2014-01-01
,我将 2 个月设置为 pmtPeriods
。这将用 [2014-02-01, 2014-02-01]
填充我的数组。如果我将 pmtPeriods
设为 3,且开始日期相同,则结果为 [2014-03-01, 2014-03-01, 2014-03-01]
。这是错误的。
使用 pmtPeriods 2 我想要结果:
[2014-02-01, 2014-03-01]
而不是
[2014-02-01, 2014-02-01]
最佳答案
您将 startDate 添加到 dateData 数组中 3 次。这只是添加对在循环中更新的 startDate 值的引用。变化:
dateData[i] = startDate;
至
dateData[i] = new Date(startDate);
关于javascript - 使用循环用月份填充数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22099016/