if / else中的逻辑(javascript)

时间:2013-04-29 18:00:29

标签: javascript

在javascript中有一个小的if / else问题。我没有看到逻辑......

该功能应检查是否存在两个日期,如果不存在则发出警报。如果一切正常,那就应该这样说......

function update_booking() {
    //from_date = The date of arrival
    //to_date = The date of departure

    var alert = ""; //reset alerts

    //get variables from booking form input
    var from_date = new Date(document.getElementById('from').value);
    var to_date = new Date(document.getElementById('to').value);

    //if arrival and departure date is present
    if(from_date && to_date) {
        var alert = "Everything is OK";
    }

    //if one or two dates are missing
    else {
        //if arrival and departure dates are missing
        if(from_date == 'undefined' || to_date == 'undefined'){
            var alert = "Arrival date and departure date are missing";  
        }

        //if from_date is missing update with value from to_date
        if(from_date == 'undefined') {
            var alert = "Arrival date are missing";
        }

        //if to_date is missing update with value from from_date
        if(from_date == 'undefined') {
            var alert = "Departure date are missing";
        }
    } //end else if one or more date(s) missing

    //write alerts
    document.getElementById('alert').innerHTML = alert;
}

4 个答案:

答案 0 :(得分:3)

如果Date的值无效,new Date(datestring)将返回非数字(NaN)的对象。

例如,new Date("")new Date(" ")都返回NaN对象,而new Date("04-29-2013")则不返回。

因此,我建议您使用undefined将搜索isNaN()更改为NaN,如下所示:

if(isNaN(from_date) || isNaN(to_date)){

答案 1 :(得分:1)

new Date不会返回undefined

> new Date("")
Invalid Date

所以看看你的代码

if(from_date == 'undefined' || to_date == 'undefined'){

永远不会进入if语句。

要检查日期是否有效,您需要use isNaN with getTime()

答案 2 :(得分:0)

试试这个:

function update_booking() {
//from_date = The date of arrival
//to_date = The date of departure
//get variables from booking form input
var from_date = document.getElementById('from').value;
var to_date =document.getElementById('to').value;

//if arrival and departure date is present
if(from_date && to_date) {
    alert( "Everything is OK");
}

//if one or two dates are missing
else {
    //if arrival and departure dates are missing
    if(from_date == ""|| to_date == ""){
        alert("Arrival date or departure date are missing");  
    }

    //if from_date is missing update with value from to_date
    if(from_date == "") {
        alert("Arrival date are missing");
    }

    //if to_date is missing update with value from from_date
    if(to_date == "") {
        alert("Departure date are missing");
    }
} //end else if one or more date(s) missing

}

答案 3 :(得分:-1)

试试这个: from_date == undefined 而不是from_date == 'undefined'