javascript - 使用循环用月份填充数组

标签 javascript jquery arrays loops

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/

相关文章:

c - 数组下标不是整数

javascript - NodeJS 确定驱动器是否可移动

jquery - 从查找、序列化 Jquery 中排除具有特定值的字段

c# - 不明显的数组索引

javascript - jQuery 慢压表

javascript - 如何在元素上设置默认 focus()

javascript - 如何检查数组中的数字序列是否增加一或多于一?

javascript - 对对象的两个引用,但是当修改它时,第二个仍然显示未更改的对象

javascript - 距离 service.getdistancematrix 从未被调用(谷歌地图 API)

javascript - jQuery : check if label by a specific name exists