Javascript 日期时间比较返回 false,但分支 stmt 仍然执行

Javascript date time comparison returns false but branch stmt still executed

本文关键字:stmt 分支 执行 时间 日期 比较 返回 false Javascript      更新时间:2023-09-26

我对这种Javascript行为感到困惑。检查此代码。

var NoOfMonthsElapsed = 6; //Should be >= 1 and <= 12
var MsgURL = "about:blank";
var PopupTitle = "ContactInfoUpdate";
var OptionString = "height=165,width=400,menubar=0,toolbar=0,location=1,status=0,resizable=0,status=0,HAlign=center,top=300";
var lastUpdatedDate = crmForm.all.dxb_lastcontactinfoupdatedon.DataValue; //Reads a field with date value = 01 Jan 2010
if (lastUpdatedDate)
{
  var month = lastUpdatedDate.getMonth();
  var year  = lastUpdatedDate.getYear();
  var date  = lastUpdatedDate.getDate();
  month = month + NoOfMonthsElapsed;
  year  = year  + parseInt(month / 11);
  month = (month % 11);
  var today = new Date();
  var showPopupAfterDate = new Date();
  showPopupAfterDate.setYear(year);
  showPopupAfterDate.setMonth(month);
  var alertMsg  = "LastUpdatedDate          = "+ lastUpdatedDate + "'n"
  var alertMsg += "Today                    = "+ today + "'n"
  var alertMsg += "PopupAfterDate           = "+ showPopupAfterDate + "'n"
  var alertMsg += "Today>showPopupAfterDate = "+ (today>showPopupAfterDate) + "'n"
  alert(alertMsg);
  if (today>showPopupAfterDate); 
  {
    window.open(MsgURL, PopupTitle, OptionString);
  }
}
else 
{
  window.open(MsgURL, PopupTitle, OptionString);
}


//
// It displays the following output
//
LastUpdatedDate          = Wed May 18 20:56:00 UTC+0400 2011
Today                    = Fri May 18 20:23:49 UTC+0400 2011
PopupAfterDate           = Fri Nov 18 20:23:49 UTC+0400 2011
Today>showPopupAfterDate = false

为什么今天显示为星期五五月18 2011... 虽然五月18 2011是星期三为什么弹出窗口日期显示为星期五十一月18 2011...即使日期比较返回假;窗口打开仍然被执行。

你的{}很乱,你在错误的地方有;

if (lastUpdatedDate) {   
    ....
    if (today>showPopupAfterDate)    { // notice I removed ;
        window.open(MsgURL, PopupTitle, OptionString);   
    } 
} else  {
   window.open(MsgURL, PopupTitle, OptionString); 
}

尾随分号关闭if语句:

if (today>showPopupAfterDate);
// --------------------------^

发现问题:

  if (today>showPopupAfterDate) //<-- remove the `;`
  {
    window.open(MsgURL, PopupTitle, OptionString);
  }

你的代码正在运行 if,停止,然后执行下一个语句,即window.open