calpa / calpa.github.io

Comments section
https://calpa.github.io
MIT License
8 stars 0 forks source link

深入淺出代碼優化﹣if/else | Calpa's Blog #107

Open calpa opened 5 years ago

calpa commented 5 years ago

https://calpa.me/2018/10/22/javascript-if-else-in-depth

對於代碼裡面的 if else,我們可以使用邏輯判斷式,或更好的三元判斷式來優化代碼。除了可以降低維護項目的成本之外,還可以提升代碼可讀性。就讓我們從最簡單的 if else 例子開始吧。

calpa commented 5 years ago

2018年10月22日,Github 出現大規模的錯誤:We continue working to repair a data storage system for GitHub.com. You may see inconsistent results during this process.

直到 10月23日早上7時3分,Github 才回復正常。

詳見:https://status.github.com/messages

horsekitlin commented 5 years ago

不要濫用複雜的 && 和 || 會造成閱讀上的問題

let xmlhttp = null;

if (window.XMLHttpRequest) {
  // 現代瀏覽器
  xmlhttp = new XMLHttpRequest();
} else if (window.ActiveXObject) {
  // 舊 IE 版本 (IE <= 6)
  xmlhttp = new ActiveXObject('Microsoft.XMLHTTP');
}

這個範例也不太適合使用 if else 用 early return 會更適合

const getXMLHttpRequest = ({XMLHttpRequest, ActiveXObject}) => {
  if(XMLHttpRequest)  return  new XMLHttpRequest();
  if(ActiveXObject) return new ActiveXObject('Microsoft.XMLHTTP');
  return null;
}

const xmlHttp = getXMLHttpRequest(window);