尽管使用 ++,但循环计数器增加 "exponentially"

While loop counter increasing "exponentially" in spite of using ++

背景资料

我正在设置一个根据开始日期和结束日期创建日期数组的函数。

该函数将接收开始日期和结束日期,这些日期首先被格式化为 year-month-dayT12:00:00:00 格式,然后以 .getTime() 格式转换为毫秒。

我的脚本

我制作了以下脚本来创建数组。

var $date_array = [];

function calc_workdays_between_dates (a, b) {

    function $create_date_array ($start_date, $end_date) {

        var $counter    = 0;

        while ($start_date !== $end_date) {

            var x = new Date($start_date);

            x.setDate(x.getDate() + $counter);
            $date_array.push(x);
            $start_date = x.getTime();
            $counter++; 
        }
    }

    $create_date_array (a, b);
}

请注意,将 $create_date_array 函数嵌套在 $calc_workdays_between_dates 函数中是有原因的。现在我已经删除了 $calc_workdays_between_dates 函数的所有其他部分,只关注手头的问题(我也在 运行 对这个精简版本进行测试 - 所以函数的其余部分是不会影响任何东西)。

我的问题

例1:

如果我用 calc_workdays_between_dates (x1, x2); 调用函数,其中:

x1 = new Date("2015-04-04") //formatted and converted to ms before invoking function
x2 = new Date("2015-04-07")

它导致 $date_array 获得以下内容:

Sat Apr 04 2015 12:00:00 GMT+0200 (CEST)
Sun Apr 05 2015 12:00:00 GMT+0200 (CEST)
Tue Apr 07 2015 12:00:00 GMT+0200 (CEST)

如您所见,该函数出于某种原因跳过星期一(总共一天)。

例二:

x1 = new Date("2015-04-04") //formatted and converted to ms before invoking function
x2 = new Date("2015-04-10")

结果:

Sat Apr 04 2015 12:00:00 GMT+0200 (CEST)
Sun Apr 05 2015 12:00:00 GMT+0200 (CEST)
Tue Apr 07 2015 12:00:00 GMT+0200 (CEST)
Fri Apr 10 2015 12:00:00 GMT+0200 (CEST)

如您所见,该函数以某种方式跳过了星期一、星期三和星期四(总共 3 天)。

例3:

x1 = new Date("2015-04-04") //formatted and converted to ms before invoking function
x2 = new Date("2015-04-14")

结果:

Sat Apr 04 2015 12:00:00 GMT+0200 (CEST)
Sun Apr 05 2015 12:00:00 GMT+0200 (CEST)
Tue Apr 07 2015 12:00:00 GMT+0200 (CEST)
Fri Apr 10 2015 12:00:00 GMT+0200 (CEST)
Tue Apr 14 2015 12:00:00 GMT+0200 (CEST)

如您所见,此实例中的函数会跳过星期一、星期三、星期四、星期六、星期日和星期一(总共 6 天)。

例4:

x1 = new Date("2015-04-04") //formatted and converted to ms before invoking function
x2 = new Date("2015-04-08")

导致函数不工作。似乎 while 循环无休止地继续 运行。

我的问题

是什么让脚本跳过几天?

您根据 $start_datecounter 计算下一个日期。但是,在 while 循环中 $start_date 被重新分配,因此不再代表开始日期。因此它不应该增加 counter,而只能增加一个。

正确的解决方案是:

while ($start_date !== $end_date) {
    var x = new Date($start_date);
    x.setDate(x.getDate() + 1);
    $date_array.push(x);
    $start_date = x.getTime();
}