5個小技巧讓你寫出更好的 JavaScript 條件語句

來源 |?http://www.fly63.com/article/detial/1192

在使用?JavaScript?時,我們常常要寫不少的條件語句。這里有五個小技巧,可以讓你寫出更干凈、漂亮的條件語句。

?1、使用 Array.includes 來處理多重條件

舉個栗子 :

// 條件語句functiontest(fruit){if(fruit =='apple'|| fruit =='strawberry') {console.log('red');? }}

乍一看,這么寫似乎沒什么大問題。然而,如果我們想要匹配更多的紅色水果呢,比方說『櫻桃』和『蔓越莓』?我們是不是得用更多的 || 來擴展這條語句?

我們可以使用 Array.includes重寫以上條件句。

functiontest(fruit){// 把條件提取到數(shù)組中constredFruits = ['apple','strawberry','cherry','cranberries'];if(redFruits.includes(fruit)) {console.log('red');? }}

我們把紅色的水果(條件)都提取到一個數(shù)組中,這使得我們的代碼看起來更加整潔。

2、少寫嵌套,盡早返回

讓我們?yōu)橹暗睦犹砑觾蓚€條件:

如果沒有提供水果,拋出錯誤。

如果該水果的數(shù)量大于 10,將其打印出來。

functiontest(fruit, quantity){constredFruits = ['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!');? ? }}// 測試結(jié)果test(null);// 報錯:No fruitstest('apple');// 打?。簉edtest('apple',20);// 打?。簉ed,big quantity

讓我們來仔細看看上面的代碼,我們有:

1 個 if/else 語句來篩選無效的條件

3 層 if 語句嵌套(條件 1,2 & 3)

就我個人而言,我遵循的一個總的規(guī)則是當發(fā)現(xiàn)無效條件時盡早返回。

/_ 當發(fā)現(xiàn)無效條件時盡早返回 _/functiontest(fruit, quantity){constredFruits = ['apple','strawberry','cherry','cranberries'];// 條件 1:盡早拋出錯誤if(!fruit) thrownewError('No fruit!');// 條件2:必須為紅色if(redFruits.includes(fruit)) {console.log('red');// 條件 3:必須是大量存在if(quantity >10) {console.log('big quantity');? ? }? }}

如此一來,我們就少寫了一層嵌套。這是種很好的代碼風格,尤其是在 if 語句很長的時候(試想一下,你得滾動到底部才能知道那兒還有個 else 語句,是不是有點不爽)。

如果反轉(zhuǎn)一下條件,我們還可以進一步地減少嵌套層級。注意觀察下面的條件 2 語句,看看是如何做到這點的:

/_ 當發(fā)現(xiàn)無效條件時盡早返回 _/functiontest(fruit, quantity){constredFruits = ['apple','strawberry','cherry','cranberries'];if(!fruit) thrownewError('No fruit!');// 條件 1:盡早拋出錯誤if(!redFruits.includes(fruit))return;// 條件 2:當 fruit 不是紅色的時候,直接返回console.log('red');// 條件 3:必須是大量存在if(quantity >10) {console.log('big quantity');? }}

通過反轉(zhuǎn)條件 2 的條件,現(xiàn)在我們的代碼已經(jīng)沒有嵌套了。當我們代碼的邏輯鏈很長,并且希望當某個條件不滿足時不再執(zhí)行之后流程時,這個技巧會很好用。

然而,并沒有任何硬性規(guī)則要求你這么做。這取決于你自己,對你而言,這個版本的代碼(沒有嵌套)是否要比之前那個版本(條件 2 有嵌套)的更好、可讀性更強?

是我的話,我會選擇前一個版本(條件 2 有嵌套)。原因在于:

這樣的代碼比較簡短和直白,一個嵌套的 if 使得結(jié)構(gòu)更加清晰。

條件反轉(zhuǎn)會導(dǎo)致更多的思考過程(增加認知負擔)。

因此,始終追求更少的嵌套,更早地返回,但是不要過度。感興趣的話,這里有篇關(guān)于這個問題的文章以及 StackOverflow 上的討論:

Avoid Else, Return Early?by Tim Oxley

StackOverflow discussion?on if/else coding style

3、使用函數(shù)默認參數(shù)和解構(gòu)

我猜你也許很熟悉以下的代碼,在?JavaScript?中我們經(jīng)常需要檢查 null / undefined 并賦予默認值:

functiontest(fruit, quantity){if(!fruit)return;constq = quantity ||1;// 如果沒有提供 quantity,默認為 1console.log(`We have${q}${fruit}!`);}//測試結(jié)果test('banana');// We have 1 banana!test('apple',2);// We have 2 apple!

事實上,我們可以通過函數(shù)的默認參數(shù)來去掉變量 q。

functiontest(fruit, quantity =1){// 如果沒有提供 quantity,默認為 1if(!fruit)return;console.log(`We have${quantity}${fruit}!`);}//測試結(jié)果test('banana');// We have 1 banana!test('apple',2);// We have 2 apple!

是不是更加簡單、直白了?請注意,所有的函數(shù)參數(shù)都可以有其默認值。舉例來說,我們同樣可以為 fruit 賦予一個默認值:function test(fruit = ‘unknown’, quantity = 1)。

那么如果 fruit 是一個對象(Object)呢?我們還可以使用默認參數(shù)嗎?

functiontest(fruit){// 如果有值,則打印出來if(fruit && fruit.name)? {console.log (fruit.name);}else{console.log('unknown');? }}//測試結(jié)果test(undefined);// unknowntest({ });// unknowntest({name:'apple',color:'red'});// apple

觀察上面的例子,當水果名稱屬性存在時,我們希望將其打印出來,否則打印『unknown』。我們可以通過默認參數(shù)和解構(gòu)賦值的方法來避免寫出 fruit && fruit.name 這種條件。

// 解構(gòu) —— 只得到 name 屬性// 默認參數(shù)為空對象 {}functiontest({name} = {}){console.log (name ||'unknown');}//測試結(jié)果test(undefined);// unknowntest({ });// unknowntest({name:'apple',color:'red'});// apple

既然我們只需要 fruit 的 name 屬性,我們可以使用 {name}來將其解構(gòu)出來,之后我們就可以在代碼中使用 name 變量來取代 fruit.name。

我們還使用 {}?作為其默認值。

如果我們不這么做的話,在執(zhí)行 test(undefined) 時,你會得到一個錯誤 Cannot destructure property name of ‘undefined’ or ‘null’.,因為 undefined 上并沒有 name 屬性。

(譯者注:這里不太準確,其實因為解構(gòu)只適用于對象(Object),而不是因為undefined 上并沒有 name 屬性(空對象上也沒有)。參考解構(gòu)賦值 - MDN)

如果你不介意使用第三方庫的話,有一些方法可以幫助減少空值(null)檢查:

使用?Lodash get?函數(shù)

使用 Facebook 開源的?idx?庫(需搭配 Babeljs)

這里有一個使用 Lodash 的例子:

//? 使用 lodash 庫提供的 _ 方法functiontest(fruit){console.log(_.get(fruit,'name','unknown');// 獲取屬性 name 的值,如果沒有,設(shè)為默認值 unknown}//測試結(jié)果test(undefined);// unknowntest({ });// unknowntest({name:'apple',color:'red'});// apple

你可以在這里運行演示代碼。另外,如果你偏愛函數(shù)式編程(FP),你可以選擇使用?Lodash fp——函數(shù)式版本的 Lodash(方法名變?yōu)?get 或 getOr)。

4、相較于 switch,Map / Object 也許是更好的選擇

讓我們看下面的例子,我們想要根據(jù)顏色打印出各種水果:

functiontest(color){// 使用 switch case 來找到對應(yīng)顏色的水果switch(color) {case'red':return['apple','strawberry'];case'yellow':return['banana','pineapple'];case'purple':return['grape','plum'];default:return[];? }}//測試結(jié)果test(null);// []test('yellow');// ['banana', 'pineapple']

上面的代碼看上去并沒有錯,但是就我個人而言,它看上去很冗長。同樣的結(jié)果可以通過對象字面量來實現(xiàn),語法也更加簡潔:

// 使用對象字面量來找到對應(yīng)顏色的水果constfruitColor = {red: ['apple','strawberry'],yellow: ['banana','pineapple'],purple: ['grape','plum']? };functiontest(color){returnfruitColor[color] || [];}

或者,你也可以使用 Map 來實現(xiàn)同樣的效果:

// 使用 Map 來找到對應(yīng)顏色的水果constfruitColor = newMap().set('red', ['apple','strawberry']).set('yellow', ['banana','pineapple']).set('purple', ['grape','plum']);functiontest(color){returnfruitColor.get(color) || [];}

Map 是 ES2015 引入的新的對象類型,允許你存放鍵值對。

那是不是說我們應(yīng)該禁止使用 switch 語句?別把自己限制住。我自己會在任何可能的時候使用對象字面量,但是這并不是說我就不用 switch,這得視場景而定。

Todd Motto 有一篇文章深入討論了 switch 語句和對象字面量,你也許會想看看。

懶人版:重構(gòu)語法

就以上的例子,事實上我們可以通過重構(gòu)我們的代碼,使用 Array.filter 實現(xiàn)同樣的效果。

constfruits = [{name:'apple',color:'red'},{name:'strawberry',color:'red'},{name:'banana',color:'yellow'},{name:'pineapple',color:'yellow'},{name:'grape',color:'purple'},{name:'plum',color:'purple'}];functiontest(color){// 使用 Array filter 來找到對應(yīng)顏色的水果returnfruits.filter(f=>f.color == color);}

解決問題的方法永遠不只一種。對于這個例子我們展示了四種實現(xiàn)方法。Coding is fun!

5、使用 Array.every 和 Array.some 來處理全部/部分滿足條件

最后一個小技巧更多地是關(guān)于使用新的(也不是很新了)JavaScript?數(shù)組函數(shù)來減少代碼行數(shù)。觀察以下的代碼,我們想要檢查是否所有的水果都是紅色的:

constfruits = [{name:'apple',color:'red'},{name:'banana',color:'yellow'},{name:'grape',color:'purple'}? ];functiontest(){letisAllRed =true;// 條件:所有的水果都必須是紅色for(letfoffruits) {if(!isAllRed)break;isAllRed = (f.color =='red');? }console.log(isAllRed);// false}

這段代碼也太長了!我們可以通過 Array.every 來縮減代碼

constfruits = [{name:'apple',color:'red'},{name:'banana',color:'yellow'},{name:'grape',color:'purple'}? ];functiontest(){// 條件:(簡短形式)所有的水果都必須是紅色constisAllRed = fruits.every(f=>f.color =='red');console.log(isAllRed);// false}

清晰多了對吧?類似的,如果我們想要檢查是否有至少一個水果是紅色的,我們可以使用 Array.some 僅用一行代碼就實現(xiàn)出來。

constfruits = [{name:'apple',color:'red'},{name:'banana',color:'yellow'},{name:'grape',color:'purple'}];functiontest(){// 條件:至少一個水果是紅色的constisAnyRed = fruits.some(f=>f.color =='red');console.log(isAnyRed);// true}

總結(jié)

讓我們一起寫出可讀性更高的代碼吧。希望這篇文章能給你們帶來一些幫助。

就是這樣啦~ ?Happy coding!


?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容