Javascript while循环无限循环

时间:2013-04-09 21:04:09

标签: javascript loops

我不是所有经验丰富的代码而且我被困在下面的代码块底部的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 ";

1 个答案:

答案 0 :(得分:3)

问题在于此行target.setDate(target.getDate() + 1);您更新了target,但您永远不会更新targetDaytargetDatetargetMonth变量......所以checkIfClosedOnTarget()函数不断传递相同的值,从而导致无限循环

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

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

     // update parameters
     targetDay = target.getDay();
     targetDate = target.getDate();
     targetMonth = target.getMonth();
}