0

我对代码的经验并不多,我被困在下面代码块底部的 while 循环中

我的代码应该获取日期,检查今天是否是我们不发货的日子(星期六、星期日、节假日),如果是,则添加 1 天,直到找到我们营业的第二天并将其写入文档。

var target = new Date();
var targetDay = target.getDay();
var targetDate = target.getDate();
var targetMonth = target.getMonth();

function checkIfClosedOnTarget(targetDay,targetDate,targetMonth){
    var areOpenOnTarget = true;
    if(
         targetDay == 0 || 
         targetDay == 6  ||
         (targetDate == 1 && targetMonth == 0) || // New Year's Day
         (targetMonth == 4 && targetDate >= 25 &&  targetDay == 1) || // Memorial Day
         (targetMonth == 6 && targetDate == 4) || //Independence Day
         (targetMonth == 8 && targetDate <= 7 && targetDay == 1)|| //Labor Day
         (targetMonth == 10 && targetDate <= 28 && targetDate >= 22 && targetDay == 4)|| // Thanksgiving Day
         (targetMonth == 11 && targetDate == 25)
     ){
         areOpenOnTarget = false;
     }

    if(areOpenOnTarget){
        return true;
    }else{
       return false;
    }
};

function addDaysUntilNextOpenDay() {
     while(checkIfClosedOnTarget(targetDay,targetDate,targetMonth) == false){
     target.setDate(target.getDate() + 1);
     }
 };
addDaysUntilNextOpenDay();

document.write("<p>Next shipment will ship out on " + target.getMonth() + " " +   target.getDate + ", " + target.getYear) + " at 4:00pm Pacific Standard Time ";
4

1 回答 1

3

问题在于target.setDate(target.getDate() + 1);您更新了这一行,target但您从未更新targetDay, targetDate,targetMonth变量...因此该checkIfClosedOnTarget()函数不断传递相同的值,从而导致无限循环

因此,您可能希望在设置第二天后更新它们:

while(checkIfClosedOnTarget(targetDay,targetDate,targetMonth) === false){
     target.setDate(target.getDate() + 1);

     // update parameters
     targetDay = target.getDay();
     targetDate = target.getDate();
     targetMonth = target.getMonth();
}
于 2013-04-09T21:10:11.117 回答