簡體   English   中英

嘗試捕獲javascript的建議

[英]advice with try catch javascript

我正在嘗試使用java腳本中的try catch驗證日期輸入,但是以下代碼無法正常運行。 我希望輸入的日期不是日期時出現錯誤,應該執行捕獲,但這是我得到的。 沒有看到新的日期,也沒有顯示任何我所期望的。

console.log("min date :")
    try{
         minDate = new Date(elminDate.value)
    }
    catch(e){
        console.log("error::")
        console.log(err.name)
        console.log("changed min")
         minDate = new Date()
    }
    console.log(minDate)

    console.log("max date :" )
    try{
         maxDate = new Date(elmaxDate.value)
    }
    catch(err){
        console.log("error::")
        console.log(err.name)
        console.log("changed max")
        maxDate = new Date()
    }
    console.log(maxDate)

回應:

[Log] min date : (home.html, line 93)
[Log] Tue Aug 01 2017 02:00:00 GMT+0200 (CEST) (home.html, line 103)
[Log] max date : (home.html, line 105)
[Log] Invalid Date (home.html, line 115)

Date構造函數不會在無效日期上引發異常,而是在Date對象中生成NaN值。 您可以對此進行測試:

console.log("date :");
date = new Date(elDate.value);
if (isNaN(date)) {
    console.log("error: Invalid Date");
    console.log("changed date to now");
    date = new Date();
}
console.log(date)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM