尽管使用++,循环计数器"呈指数增长"

rab*_*tco 6 javascript counter while-loop nested-function

背景资料

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

该函数将接收开始日期和结束日期,这些日期首先被格式化为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);
}
Run Code Online (Sandbox Code Playgroud)

请注意,在$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")
Run Code Online (Sandbox Code Playgroud)

它导致$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)
Run Code Online (Sandbox Code Playgroud)

正如您所看到的那样,由于某种原因,该功能会在星期一(总共一天)跳过.

例2:

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

结果是:

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)
Run Code Online (Sandbox Code Playgroud)

正如您所看到的,该功能以某种方式跳过周一,周三和周四(总共3天).

例3:

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

结果是:

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)
Run Code Online (Sandbox Code Playgroud)

正如您所看到的,该实例中的功能会跳过周一,周三,周四,周六,周日和周一(总共6天).

例4:

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

导致功能无法正常工作.似乎while循环继续无休止地运行.

我的问题

什么使脚本跳过几天?

mvd*_*sel 7

您根据$start_date和计算下一个日期counter.但是,在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();
}
Run Code Online (Sandbox Code Playgroud)