Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
calpa opened this issue Oct 22, 2018 · 2 comments
Open

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

calpa opened this issue Oct 22, 2018 · 2 comments

Comments

@calpa
Copy link
Owner

calpa commented Oct 22, 2018

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

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

@calpa
Copy link
Owner Author

calpa commented Oct 23, 2018

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
Copy link

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

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);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants