2013-04-09 312 views
0

我不是所有经历过的代码和我卡在朝着下面的代码的Javascript while循环无限循环

我的代码块底部的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 "; 
+0

你应该只返回逻辑的句子在你的'checkIfClosedOnTarget'功能“”如果'声明:

所以你设置后的第二天,你可能要对其进行更新。其余代码是多余的。 – 2013-04-09 21:07:33

+1

我认为你可以做很多清理你的代码。例如,你有一个名为'checkIfClosedOnTarget'的方法,这意味着如果关闭,它会返回'true',但如果打开则返回true。罗嗦。尝试将其重命名为“isOpen”或“isOpenOn”。那么你真的只需要在你的大if语句中返回false,并且在它之外是真实的。根本不需要'areOpenOnTarget'变量。 – 2013-04-09 21:10:27

+0

fyi,这不是递归.... – sweetamylase 2013-04-09 21:10:37

回答

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(); 
} 
+0

+1,你已经发现了这个问题。不过,我认为将'targetDay'等作为'checkIfClosedOnTarget'中的局部变量并将'target'传递给该函数将会更加清洁。 – 2013-04-09 21:13:23

+0

@MarkPeters同意,有不同的方式传递信息。直到OP决定他们如何最好地接近它。 – sweetamylase 2013-04-09 21:19:32