- 【強制】在一個 switch 塊內,每個case要么通過 break/return 等來終止,要么注釋說明程序將繼續執行到哪一個 case 為止;在一個 switch 塊內,都必須包含一個default 語句并且 放在最后,即使它什么代碼也沒有。
- 在 if/else/for/while/do 語句中必須使用大括號,即使只有一行代碼,避免使用 下面的形式: if (condition) statements;
- 【推薦】推薦盡量少用 else, if-else 的方式可以改寫成
```
if(condition) {
return obj;
}
```
- 方式表達邏輯,【強制】請勿超過3層, 超過請使用狀態設計模式。 正例:邏輯上超過 3 層的 if-else 代碼可以使用衛語句,或者狀態模式來實現。
```
// 修改前
if(isReqeustError) {
console.log('isReqeustError is true');
}
else {
if(!classList.length) {
console.log('classList's length is zero');
}else {
console.log('classList's length is more than zero');
}
}
// 使用衛語句
if(isReqeustError) {
console.log('isReqeustError is true');
return;
}
if(!classList.length) {
console.log('classList's length is zero');
return;
}
console.log('classList's length is more than zero');
```
附:[JavaScript設計模式](http://www.hmoore.net/digest/design-pattern-of-js/128426)
-【推薦】使用三目運算,替換if else結構,精簡代碼
-【推薦】除常用方法(如 getXxx/isXxx)等外,不要在條件判斷中執行其它復雜的語句,將復 雜邏輯判斷的結果賦值給一個有意義的布爾變量名,以提高可讀性。 說明:很多 if 語句內的邏輯相當復雜,閱讀者需要分析條件表達式的最終結果,才能明確什么 樣的條件執行什么樣的語句,那么,如果閱讀者分析邏輯表達式錯誤呢?
```
//偽代碼如下
boolean existed = (file.open(fileName, "w") != null)&& (...) || (...);
if (existed) {
...
}
```