5個(gè)小技巧讓你寫出更好的 JavaScript 條件語(yǔ)句

在使用?JavaScript?時(shí),我們常常要寫不少的條件語(yǔ)句。這里有五個(gè)小技巧,可以讓你寫出更干凈、漂亮的條件語(yǔ)句。
?1、使用 Array.includes 來(lái)處理多重條件
舉個(gè)栗子 :
// 條件語(yǔ)句function test(fruit) {if (fruit == 'apple' || fruit == 'strawberry') {console.log('red');}}
function test(fruit) {// 把條件提取到數(shù)組中const redFruits = ['apple', 'strawberry', 'cherry', 'cranberries'];if (redFruits.includes(fruit)) {console.log('red');}}
2、少寫嵌套,盡早返回
如果沒有提供水果,拋出錯(cuò)誤。 如果該水果的數(shù)量大于 10,將其打印出來(lái)。
function test(fruit, quantity) {const redFruits = ['apple', 'strawberry', 'cherry', 'cranberries'];// 條件 1:fruit 必須有值if (fruit) {// 條件 2:必須為紅色if (redFruits.includes(fruit)) {console.log('red');// 條件 3:必須是大量存在if (quantity > 10) {console.log('big quantity');}}} else {thrownewError('No fruit!');}}// 測(cè)試結(jié)果test(null); // 報(bào)錯(cuò):No fruitstest('apple'); // 打印:redtest('apple', 20); // 打印:red,big quantity
1 個(gè) if/else 語(yǔ)句來(lái)篩選無(wú)效的條件 3 層 if 語(yǔ)句嵌套(條件 1,2 & 3)
/_ 當(dāng)發(fā)現(xiàn)無(wú)效條件時(shí)盡早返回 _/function test(fruit, quantity) {const redFruits = ['apple', 'strawberry', 'cherry', 'cranberries'];// 條件 1:盡早拋出錯(cuò)誤if (!fruit) thrownewError('No fruit!');// 條件2:必須為紅色if (redFruits.includes(fruit)) {console.log('red');// 條件 3:必須是大量存在if (quantity > 10) {console.log('big quantity');}}}
/_ 當(dāng)發(fā)現(xiàn)無(wú)效條件時(shí)盡早返回 _/function test(fruit, quantity) {const redFruits = ['apple', 'strawberry', 'cherry', 'cranberries'];if (!fruit) thrownewError('No fruit!'); // 條件 1:盡早拋出錯(cuò)誤if (!redFruits.includes(fruit)) return; // 條件 2:當(dāng) fruit 不是紅色的時(shí)候,直接返回console.log('red');// 條件 3:必須是大量存在if (quantity > 10) {console.log('big quantity');}}
這樣的代碼比較簡(jiǎn)短和直白,一個(gè)嵌套的 if 使得結(jié)構(gòu)更加清晰。
條件反轉(zhuǎn)會(huì)導(dǎo)致更多的思考過(guò)程(增加認(rèn)知負(fù)擔(dān))。
Avoid Else, Return Early?by Tim Oxley
StackOverflow discussion?on if/else coding style
3、使用函數(shù)默認(rèn)參數(shù)和解構(gòu)
function test(fruit, quantity) {if (!fruit) return;const q = quantity || 1; // 如果沒有提供 quantity,默認(rèn)為 1console.log(`We have ${q}${fruit}!`);}//測(cè)試結(jié)果test('banana'); // We have 1 banana!test('apple', 2); // We have 2 apple!
function test(fruit, quantity = 1) { // 如果沒有提供 quantity,默認(rèn)為 1if (!fruit) return;console.log(`We have ${quantity}${fruit}!`);}//測(cè)試結(jié)果test('banana'); // We have 1 banana!test('apple', 2); // We have 2 apple!
function test(fruit) {// 如果有值,則打印出來(lái)if (fruit && fruit.name) {console.log (fruit.name);} else {console.log('unknown');}}//測(cè)試結(jié)果test(undefined); // unknowntest({ }); // unknowntest({ name: 'apple', color: 'red' }); // apple
觀察上面的例子,當(dāng)水果名稱屬性存在時(shí),我們希望將其打印出來(lái),否則打印『unknown』。
我們可以通過(guò)默認(rèn)參數(shù)和解構(gòu)賦值的方法來(lái)避免寫出 fruit && fruit.name 這種條件。
// 解構(gòu) —— 只得到 name 屬性// 默認(rèn)參數(shù)為空對(duì)象 {}function test({name} = {}) {console.log (name || 'unknown');}//測(cè)試結(jié)果test(undefined); // unknowntest({ }); // unknowntest({ name: 'apple', color: 'red' }); // apple
既然我們只需要 fruit 的 name 屬性,我們可以使用 {name}來(lái)將其解構(gòu)出來(lái),之后我們就可以在代碼中使用 name 變量來(lái)取代 fruit.name。
我們還使用 {}?作為其默認(rèn)值。如果我們不這么做的話,在執(zhí)行 test(undefined) 時(shí),你會(huì)得到一個(gè)錯(cuò)誤 Cannot destructure property name of ‘undefined’ or ‘null’.,因?yàn)?undefined 上并沒有 name 屬性。
(譯者注:這里不太準(zhǔn)確,其實(shí)因?yàn)榻鈽?gòu)只適用于對(duì)象(Object),而不是因?yàn)閡ndefined 上并沒有 name 屬性(空對(duì)象上也沒有)。參考解構(gòu)賦值 - MDN)
如果你不介意使用第三方庫(kù)的話,有一些方法可以幫助減少空值(null)檢查:
使用?Lodash get?函數(shù)
使用 Facebook 開源的?idx?庫(kù)(需搭配 Babeljs)
這里有一個(gè)使用 Lodash 的例子:
// 使用 lodash 庫(kù)提供的 _ 方法function test(fruit) {console.log(_.get(fruit, 'name', 'unknown'); // 獲取屬性 name 的值,如果沒有,設(shè)為默認(rèn)值 unknown}//測(cè)試結(jié)果test(undefined); // unknowntest({ }); // unknowntest({ name: 'apple', color: 'red' }); // apple
你可以在這里運(yùn)行演示代碼。另外,如果你偏愛函數(shù)式編程(FP),你可以選擇使用?Lodash fp——函數(shù)式版本的 Lodash(方法名變?yōu)?get 或 getOr)。
4、相較于 switch,Map / Object 也許是更好的選擇
讓我們看下面的例子,我們想要根據(jù)顏色打印出各種水果:
function test(color) {// 使用 switch case 來(lái)找到對(duì)應(yīng)顏色的水果switch (color) {case 'red':return ['apple', 'strawberry'];case 'yellow':return ['banana', 'pineapple'];case 'purple':return ['grape', 'plum'];default:return [];}}//測(cè)試結(jié)果test(null); // []test('yellow'); // ['banana', 'pineapple']
// 使用對(duì)象字面量來(lái)找到對(duì)應(yīng)顏色的水果const fruitColor = {red: ['apple', 'strawberry'],yellow: ['banana', 'pineapple'],purple: ['grape', 'plum']};function test(color) {return fruitColor[color] || [];}
或者,你也可以使用 Map 來(lái)實(shí)現(xiàn)同樣的效果:
// 使用 Map 來(lái)找到對(duì)應(yīng)顏色的水果const fruitColor = newMap().set('red', ['apple', 'strawberry']).set('yellow', ['banana', 'pineapple']).set('purple', ['grape', 'plum']);function test(color) {return fruitColor.get(color) || [];}
懶人版:重構(gòu)語(yǔ)法
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) {// 使用 Array filter 來(lái)找到對(duì)應(yīng)顏色的水果return fruits.filter(f => f.color == color);}
解決問(wèn)題的方法永遠(yuǎn)不只一種。對(duì)于這個(gè)例子我們展示了四種實(shí)現(xiàn)方法。Coding is fun!
5、使用 Array.every 和 Array.some 來(lái)處理全部/部分滿足條件
最后一個(gè)小技巧更多地是關(guān)于使用新的(也不是很新了)JavaScript?數(shù)組函數(shù)來(lá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}
這段代碼也太長(zhǎng)了!我們可以通過(guò) Array.every 來(lái)縮減代碼。
const fruits = [{ name: 'apple', color: 'red' },{ name: 'banana', color: 'yellow' },{ name: 'grape', color: 'purple' }];function test() {// 條件:(簡(jiǎn)短形式)所有的水果都必須是紅色const isAllRed = fruits.every(f => f.color == 'red');console.log(isAllRed); // false}
const fruits = [{ name: 'apple', color: 'red' },{ name: 'banana', color: 'yellow' },{ name: 'grape', color: 'purple' }];function test() {// 條件:至少一個(gè)水果是紅色的const isAnyRed = fruits.some(f => f.color == 'red');console.log(isAnyRed); // true}
總結(jié)
讓我們一起寫出可讀性更高的代碼吧。希望這篇文章能給你們帶來(lái)一些幫助。
就是這樣啦~ ?Happy coding!

