寫好JavaScript條件語句的5條守則
原文地址:5 Tips to Write Better Conditionals in JavaScript 譯文出自:阿里云翻譯小組 譯文鏈接:https://github.com/dawn-teams/translate/blob/master/articles/5-Tips-to-Write-Better-Conditionals-in-JavaScript.md 譯者:眠云(楊濤) 校對者:也樹,Mcskiller
在用 JavaScript 工作時,我們經(jīng)常和條件語句打交道,這里有5條讓你寫出更好/干凈的條件語句的建議。
1.多重判斷時使用 Array.includes
2.更少的嵌套,盡早 return
3.使用默認參數(shù)和解構(gòu)
4.傾向于遍歷對象而不是 Switch 語句
5.對 所有/部分 判斷使用 Array.every & Array.some
6.總結(jié)
1.多重判斷時使用 Array.includes
讓我們看一下下面這個例子:
//?condition
function?test(fruit)?{
??if?(fruit?==?'apple'?||?fruit?==?'strawberry')?{
????console.log('red');
??}
}
第一眼,上面這個例子看起來沒問題。如果我們有更多名字叫 cherry 和 cranberries 的紅色水果呢?我們準備用更多的 || 來拓展條件語句嗎?
我們可以用 Array.includes (Array.includes)重寫條件語句。
function?test(fruit)?{
??const?redFruits?=?['apple',?'strawberry',?'cherry',?'cranberries'];
??if?(redFruits.includes(fruit))?{
????console.log('red');
??}
}
我們把紅色的水果(red fruits)這一判斷條件提取到一個數(shù)組。這樣一來,代碼看起來更整潔。
2.更少的嵌套,盡早 Return
讓我們拓展上一個例子讓它包含兩個條件。
如果沒有傳入?yún)?shù) fruit,拋出錯誤接受 quantity參數(shù),并且在quantity大于10時打印出來
function?test(fruit,?quantity)?{
??const?redFruits?=?['apple',?'strawberry',?'cherry',?'cranberries'];
??//?條件?1:?fruit?必須有值
??if?(fruit)?{
????//?條件?2:?必須是red的
????if?(redFruits.includes(fruit))?{
??????console.log('red');
??????//?條件?3:?quantity大于10
??????if?(quantity?>?10)?{
????????console.log('big?quantity');
??????}
????}
??}?else?{
????throw?new?Error('No?fruit!');
??}
}
//?測試結(jié)果
test(null);?//?error:?No?fruits
test('apple');?//?print:?red
test('apple',?20);?//?print:?red,?big?quantity
在上面的代碼, 我們有:
1個 if/else 語句篩選出無效的語句 3層if嵌套語句 (條件 1, 2 & 3)
我個人遵循的規(guī)則一般是在發(fā)現(xiàn)無效條件時,盡早Return。
/_?當發(fā)現(xiàn)無效語句時,盡早Return?_/
function?test(fruit,?quantity)?{
??const?redFruits?=?['apple',?'strawberry',?'cherry',?'cranberries'];
??//?條件?1:?盡早拋出錯誤
??if?(!fruit)?throw?new?Error('No?fruit!');
??//?條件?2:?必須是紅色的
??if?(redFruits.includes(fruit))?{
????console.log('red');
????//?條件?3:?必須是大質(zhì)量的
????if?(quantity?>?10)?{
??????console.log('big?quantity');
????}
??}
}
這樣一來,我們少了一層嵌套語句。這種編碼風格非常好,尤其是當你有很長的if語句的時候(想象你需要滾動到最底層才知道還有else語句,這并不酷)
我們可以通過 倒置判斷條件 & 盡早return 進一步減少if嵌套。看下面我們是怎么處理判斷 條件2 的:
/_?當發(fā)現(xiàn)無效語句時,盡早Return?_/
function?test(fruit,?quantity)?{
??const?redFruits?=?['apple',?'strawberry',?'cherry',?'cranberries'];
??//?條件?1:?盡早拋出錯誤
??if?(!fruit)?throw?new?Error('No?fruit!');
??//?條件?2:?當水果不是紅色時停止繼續(xù)執(zhí)行
??if?(!redFruits.includes(fruit))?return;?
??console.log('red');
??//?條件?3:?必須是大質(zhì)量的
??if?(quantity?>?10)?{
????console.log('big?quantity');
??}
}
通過倒置判斷條件2,我們的代碼避免了嵌套語句。這個技巧在我們需要進行很長的邏輯判斷時是非常有用的,特別是我們希望能夠在條件不滿足時能夠停止下來進行處理。
而且這么做并不困難。問問自己,這個版本(沒有嵌套)是不是比之前的(兩層條件嵌套)更好,可讀性更高?
但對于我,我會保留先前的版本(包含兩層嵌套)。這是因為:
代碼比較短且直接,包含if嵌套的更清晰 倒置判斷條件可能加重思考的負擔(增加認知載荷)
因此,應(yīng)當盡力減少嵌套和盡早return,但不要過度。如果你感興趣的話,可以看一下關(guān)于這個話題的一篇文章和 StackOverflow 上的討論。
Avoid Else, Return Early by Tim Oxley StackOverflow discussion on if/else coding style
3.使用默認參數(shù)和解構(gòu)
我猜下面的代碼你可能會熟悉,在JavaScript中我們總是需要檢查 null / undefined的值和指定默認值:
function?test(fruit,?quantity)?{
??if?(!fruit)?return;
??//?如果?quantity?參數(shù)沒有傳入,設(shè)置默認值為?1
??const?q?=?quantity?||?1;?
??console.log(`We?have?${q}?${fruit}!`);
}
//test?results
test('banana');?//?We?have?1?banana!
test('apple',?2);?//?We?have?2?apple!
實際上,我們可以通過聲明 默認函數(shù)參數(shù) 來消除變量 q。
function?test(fruit,?quantity?=?1)?{
??//?如果?quantity?參數(shù)沒有傳入,設(shè)置默認值為?1
??if?(!fruit)?return;
??console.log(`We?have?${quantity}?${fruit}!`);
}
//test?results
test('banana');?//?We?have?1?banana!
test('apple',?2);?//?We?have?2?apple!
這更加直觀,不是嗎?注意,每個聲明都有自己的默認參數(shù).
例如,我們也能給fruit分配默認值:function test(fruit = 'unknown', quantity = 1)。
如果fruit是一個object會怎么樣?我們能分配一個默認參數(shù)嗎?
function?test(fruit)?{?
??//?當值存在時打印?fruit?的值
??if?(fruit?&&?fruit.name)??{
????console.log?(fruit.name);
??}?else?{
????console.log('unknown');
??}
}
//test?results
test(undefined);?//?unknown
test({?});?//?unknown
test({?name:?'apple',?color:?'red'?});?//?apple
看上面這個例子,我們想打印 fruit 對象中可能存在的 name 屬性。否則我們將打印unknown。我們可以通過默認參數(shù)以及解構(gòu)從而避免判斷條件 fruit && fruit.name
//?解構(gòu)?-?僅僅獲取?name?屬性
//?為其賦默認值為空對象
function?test({name}?=?{})?{
??console.log?(name?||?'unknown');
}
//?test?results
test(undefined);?//?unknown
test({?});?//?unknown
test({?name:?'apple',?color:?'red'?});?//?apple
由于我們只需要 name 屬性,我們可以用 {name} 解構(gòu)出參數(shù),然后我們就能使用變量 name 代替 fruit.name。
我們也需要聲明空對象 {} 作為默認值。如果我們不這么做,當執(zhí)行 test(undefined) 時,你將得到一個無法對 undefined 或 null 解構(gòu)的的錯誤。因為在 undefined 中沒有 name 屬性。
如果你不介意使用第三方庫,這有一些方式減少null的檢查:
使用 Lodash get函數(shù) 使用Facebook開源的idx庫(with Babeljs)
這是一個使用Lodash的例子:
function?test(fruit)?{
??//?獲取屬性名,如果屬性名不可用,賦默認值為?unknown
??console.log(__.get(fruit,?'name',?'unknown');?
}
//?test?results
test(undefined);?//?unknown
test({?});?//?unknown
test({?name:?'apple',?color:?'red'?});?//?apple
你可以在jsbin運行demo代碼。除此之外,如果你是函數(shù)式編程的粉絲,你可能選擇使用 Lodash fp,Lodash的函數(shù)式版本(方法變更為get或者getOr)。
4.傾向于對象遍歷而不是Switch語句
讓我們看下面這個例子,我們想根據(jù) color 打印出水果:
function?test(color)?{
??//?使用條件語句來尋找對應(yīng)顏色的水果
??switch?(color)?{
????case?'red':
??????return?['apple',?'strawberry'];
????case?'yellow':
??????return?['banana',?'pineapple'];
????case?'purple':
??????return?['grape',?'plum'];
????default:
??????return?[];
??}
}
//?test?results
test(null);?//?[]
test('yellow');?//?['banana',?'pineapple']
上面的代碼看起來沒有錯誤,但是我找到了一些累贅。用對象遍歷實現(xiàn)相同的結(jié)果,語法看起來更簡潔:
const?fruitColor?=?{
??red:?['apple',?'strawberry'],
??yellow:?['banana',?'pineapple'],
??purple:?['grape',?'plum']
};
function?test(color)?{
??return?fruitColor[color]?||?[];
}
或者你也可以使用 Map實現(xiàn)相同的結(jié)果:
??const?fruitColor?=?new?Map()
????.set('red',?['apple',?'strawberry'])
????.set('yellow',?['banana',?'pineapple'])
????.set('purple',?['grape',?'plum']);
function?test(color)?{
??return?fruitColor.get(color)?||?[];
}
Map是一種在 ES2015 規(guī)范之后實現(xiàn)的對象類型,允許你存儲 key 和 value 的值。
但我們是否應(yīng)當禁止switch語句的使用呢?答案是不要限制你自己。從個人來說,我會盡可能的使用對象遍歷,但我并不嚴格遵守它,而是使用對當前的場景更有意義的方式。
Todd Motto有一篇關(guān)于 switch 語句對比對象遍歷的更深入的文章,你可以在這個地方閱讀
TL;DR; 重構(gòu)語法
在上面的例子,我們能夠用Array.filter 重構(gòu)我們的代碼,實現(xiàn)相同的效果。
?const?fruits?=?[
????{?name:?'apple',?color:?'red'?},?
????{?name:?'strawberry',?color:?'red'?},?
????{?name:?'banana',?color:?'yellow'?},?
????{?name:?'pineapple',?color:?'yellow'?},?
????{?name:?'grape',?color:?'purple'?},?
????{?name:?'plum',?color:?'purple'?}
];
function?test(color)?{
??return?fruits.filter(f?=>?f.color?==?color);
}
有著不止一種方法能夠?qū)崿F(xiàn)相同的結(jié)果,我們以上展示了 4 種。
5.對 所有/部分 判斷使用Array.every & Array.some
這最后一個建議更多是關(guān)于利用 JavaScript Array 的內(nèi)置方法來減少代碼行數(shù)。看下面的代碼,我們想要檢查是否所有水果都是紅色:
const?fruits?=?[
????{?name:?'apple',?color:?'red'?},
????{?name:?'banana',?color:?'yellow'?},
????{?name:?'grape',?color:?'purple'?}
??];
function?test()?{
??let?isAllRed?=?true;
??//?條件:所有水果都是紅色
??for?(let?f?of?fruits)?{
????if?(!isAllRed)?break;
????isAllRed?=?(f.color?==?'red');
??}
??console.log(isAllRed);?//?false
}
代碼那么長!我們可以通過 Array.every減少代碼行數(shù):
const?fruits?=?[
????{?name:?'apple',?color:?'red'?},
????{?name:?'banana',?color:?'yellow'?},
????{?name:?'grape',?color:?'purple'?}
??];
function?test()?{
??const?isAllRed?=?fruits.every(f?=>?f.color?==?'red');
??console.log(isAllRed);?//?false
}
現(xiàn)在更簡潔了,不是嗎?相同的方式,如果我們想測試是否存在紅色的水果,我們可以使用 Array.some 一行代碼實現(xiàn)。
const?fruits?=?[
????{?name:?'apple',?color:?'red'?},
????{?name:?'banana',?color:?'yellow'?},
????{?name:?'grape',?color:?'purple'?}
];
function?test()?{
??//?條件:任何一個水果是紅色
??const?isAnyRed?=?fruits.some(f?=>?f.color?==?'red');
??console.log(isAnyRed);?//?true
}
6.總結(jié)
讓我們一起生產(chǎn)更多可讀性高的代碼。我希望你能從這篇文章學到東西。
這就是所有的內(nèi)容。編碼快樂!

我是依揚,螞蟻集團-保險團隊正在大量招聘中,詳情見:我們是螞蟻保險前端團隊,我們今年在做什么,有興趣快來聯(lián)系我吧[email protected]
