2013-08-06 86 views
1

這2個代碼有什麼區別?Javascript if語句和&&運算符區別

之一:如果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!'); 
      } 
     } 
} 

TWO:如果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!'); 
} 

}

他們看起來都一樣給我,但只有第一個做了我想要的東西,而不是第二個繼續顯示警報消息。

+0

唯一的區別是在第一個中,如果readyState不是4,那麼您不會看到警報。 – smerny

+0

@thelmaeckman他們看起來都一樣嗎?仔細檢查邏輯... – sgroves

回答

1

就緒狀態是4之前,它是3.然後

  • 在第一殼體外部測試防止alert

  • 在第二種情況下,else條款適用所以alert被執行。

0

假設第一部分是假的。

then if的情況下,您將永遠不會進入該塊,因此您將永遠不會在第二條if語句中看到警報。如果您使用&&,則輸入else塊(如果其中任一個爲假)。

0

唯一的區別是在第一個中,如果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 
    } 
} 

他們會在功能上是一樣的。因此,如果您想要第一個,您可以根據「出錯」來輕鬆定製警報。