Javascript if语句和&&操作员差异

Javascript if statement and && operator difference

本文关键字:amp 操作员 if Javascript 语句      更新时间:2023-09-26

这两个代码之间有什么区别?

一:如果xmlhttp.readystate==4,那么如果xmlhttp.status==200,那么执行代码

function handleServerResponse(){
   if(xmlHttp.readyState==4){
            if(xmlHttp.status==200){
               xmlResponse = xmlHttp.responseXML;
               xmlDocumentElement = xmlResponse.documentElement;
               message = xmlDocumentElement.firstChild.data;
               document.getElementById('underInput').innerHTML = message;
               setTimeout('process()', 1000);
         }else{
            alert('Something went wrong!');
            }
      }
}

二:如果xmlHttp.readtState==4和xmlHttp.Status==200,则执行代码

function handleSxerverResponse(){
if(xmlHttp.readyState==4 && xmlHttp.status==200){
    xmlResponse = xmlHttp.responseXML;
    xmlDocumentElement = xmlResponse.documnetElement;
    message = xmlDocumentElement.firstChild.data;
    document.getElementById('underInput').innerHTML = message;
    setTimeout('process()', 1000);
}else{
    alert('Something went wrong!');
}   

}

它们在我看来都一样,但只有第一个做了我想做的,而第二个一直显示警报信息。

在就绪状态为4之前,它是3。然后

  • 在第一种情况下,外部测试阻止alert

  • 在第二种情况下,应用else子句,从而执行alert

假设第一部分为false。

then if的情况下,您永远不会进入块,因此您永远不会在第二个if语句中看到警报。如果使用&&,如果其中一个为false,则将进入else块。

唯一的区别是,在第一个中,如果readyState不是4,则不会看到警报。

如果你把第一个转换成这个:

function handleServerResponse() {
    if (xmlHttp.readyState == 4) {
        if (xmlHttp.status == 200) {
            xmlResponse = xmlHttp.responseXML;
            xmlDocumentElement = xmlResponse.documentElement;
            message = xmlDocumentElement.firstChild.data;
            document.getElementById('underInput').innerHTML = message;
            setTimeout('process()', 1000);
        } else {
            alert('Something went wrong!');
        }
    } else {
        alert('Something went wrong!'); //added this
    }
}

它们在功能上是一样的。因此,有了第一个,如果你愿意,你可以很容易地根据"出了问题"来定制警报。