在用 JavaScript 工做時,咱們常常和條件語句打交道,這裏有5條讓你寫出更好/乾淨的條件語句的建議。javascript
目錄:java
1.多重判斷時使用 Array.includes編程
2.更少的嵌套,儘早 return數組
3.使用默認參數和解構app
4.傾向於遍歷對象而不是 Switch 語句函數式編程
5.對 全部/部分 判斷使用 Array.every & Array.some函數
6.總結測試
讓咱們看一下下面這個例子:ui
// 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)這一判斷條件提取到一個數組。這樣一來,代碼看起來更整潔。
讓咱們拓展上一個例子讓它包含兩個條件。
若是沒有傳入參數 fruit,拋出錯誤
接受 quantity 參數,而且在 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!'); } } // 測試結果 test(null); // error: No fruits test('apple'); // print: red test('apple', 20); // print: red, big quantity
在上面的代碼, 咱們有:
1個 if/else 語句篩選出無效的語句
3層if嵌套語句 (條件 1, 2 & 3)
我我的遵循的規則通常是在發現無效條件時,儘早Return。
/_ 當發現無效語句時,儘早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: 必須是大質量的 if (quantity > 10) { console.log('big quantity'); } } }
這樣一來,咱們少了一層嵌套語句。這種編碼風格很是好,尤爲是當你有很長的if語句的時候(想象你須要滾動到最底層才知道還有else語句,這並不酷)
咱們能夠經過 倒置判斷條件 & 儘早return 進一步減小if嵌套。看下面咱們是怎麼處理判斷 條件2 的:
/_ 當發現無效語句時,儘早Return _/ function test(fruit, quantity) { const redFruits = ['apple', 'strawberry', 'cherry', 'cranberries']; // 條件 1: 儘早拋出錯誤 if (!fruit) throw new Error('No fruit!'); // 條件 2: 當水果不是紅色時中止繼續執行 if (!redFruits.includes(fruit)) return; console.log('red'); // 條件 3: 必須是大質量的 if (quantity > 10) { console.log('big quantity'); } }
經過倒置判斷條件2,咱們的代碼避免了嵌套語句。這個技巧在咱們須要進行很長的邏輯判斷時是很是有用的,特別是咱們但願可以在條件不知足時可以中止下來進行處理。
並且這麼作並不困難。問問本身,這個版本(沒有嵌套)是否是比以前的(兩層條件嵌套)更好,可讀性更高?
但對於我,我會保留先前的版本(包含兩層嵌套)。這是由於:
代碼比較短且直接,包含if嵌套的更清晰
倒置判斷條件可能加劇思考的負擔(增長認知載荷)
所以,應當盡力減小嵌套和儘早return,但不要過分。若是你感興趣的話,能夠看一下關於這個話題的一篇文章和 StackOverflow 上的討論。
Avoid Else, Return Early by Tim Oxley
StackOverflow discussion on if/else coding style
我猜下面的代碼你可能會熟悉,在JavaScript中咱們老是須要檢查 null / undefined的值和指定默認值:
function test(fruit, quantity) { if (!fruit) return; // 若是 quantity 參數沒有傳入,設置默認值爲 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!
實際上,咱們能夠經過聲明 默認函數參數 來消除變量 q。
function test(fruit, quantity = 1) { // 若是 quantity 參數沒有傳入,設置默認值爲 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!
這更加直觀,不是嗎?注意,每一個聲明都有本身的默認參數.
例如,咱們也能給fruit分配默認值:function test(fruit = 'unknown', quantity = 1)。
若是fruit是一個object會怎麼樣?咱們能分配一個默認參數嗎?
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。咱們能夠經過默認參數以及解構從而避免判斷條件 fruit && fruit.name
// 解構 - 僅僅獲取 name 屬性 // 爲其賦默認值爲空對象 function test({name} = {}) { console.log (name || 'unknown'); } // test results test(undefined); // unknown test({ }); // unknown test({ name: 'apple', color: 'red' }); // apple
因爲咱們只須要 name 屬性,咱們能夠用 {name} 解構出參數,而後咱們就能使用變量 name 代替 fruit.name。
咱們也須要聲明空對象 {} 做爲默認值。若是咱們不這麼作,當執行 test(undefined) 時,你將獲得一個沒法對 undefined 或 null 解構的的錯誤。由於在 undefined 中沒有 name 屬性。
若是你不介意使用第三方庫,這有一些方式減小null的檢查:
使用 Lodash get函數
使用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代碼。除此以外,若是你是函數式編程的粉絲,你可能選擇使用 Lodash fp,Lodash的函數式版本(方法變動爲get或者getOr)。
讓咱們看下面這個例子,咱們想根據 color 打印出水果:
function test(color) { // 使用條件語句來尋找對應顏色的水果 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']
上面的代碼看起來沒有錯誤,可是我找到了一些累贅。用對象遍歷實現相同的結果,語法看起來更簡潔:
const fruitColor = { red: ['apple', 'strawberry'], yellow: ['banana', 'pineapple'], purple: ['grape', 'plum'] }; function test(color) { return fruitColor[color] || []; }
或者你也可使用 Map實現相同的結果:
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 規範以後實現的對象類型,容許你存儲 key 和 value 的值。
但咱們是否應當禁止switch語句的使用呢?答案是不要限制你本身。從我的來講,我會盡量的使用對象遍歷,但我並不嚴格遵照它,而是使用對當前的場景更有意義的方式。
Todd Motto有一篇關於 switch 語句對比對象遍歷的更深刻的文章,你能夠在這個地方閱讀
在上面的例子,咱們可以用Array.filter 重構咱們的代碼,實現相同的效果。
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); }
有着不止一種方法可以實現相同的結果,咱們以上展現了 4 種。
這最後一個建議更可能是關於利用 JavaScript Array 的內置方法來減小代碼行數。看下面的代碼,咱們想要檢查是否全部水果都是紅色:
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減小代碼行數:
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 }
如今更簡潔了,不是嗎?相同的方式,若是咱們想測試是否存在紅色的水果,咱們可使用 Array.some 一行代碼實現。
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 }
讓咱們一塊兒生產更多可讀性高的代碼。我但願你能從這篇文章學到東西。