1. 程式人生 > >前端寫好JS條件語句的5條守則

前端寫好JS條件語句的5條守則

  在用 JavaScript 工作時,我們經常和條件語句打交道,這裡有5條讓你寫出更好/乾淨的條件語句的建議。

  1、多重判斷時使用 Array.includes

  讓我們看一下下面這個例子:

  // conditionfunction 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)這一判斷條件提取到一個數組。這樣一來,程式碼看起來更整潔。

  2、更少的巢狀,儘早 Return

  讓我們拓展上一個例子讓它包含兩個條件。

  如果沒有傳入引數 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 fruitstest('apple'); // print: redtest('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,但不要過度。

  3、使用預設引數和解構

  我猜下面的程式碼你可能會熟悉,在JavaScript中我們總是需要檢查 null / undefined的值和指定預設值:

  function test(fruit, quantity) { if (!fruit) return; // 如果 quantity 引數沒有傳入,設定預設值為 1 const q = quantity || 1; console.log(`We have ${q} ${fruit}!`);}//test resultstest('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 resultstest('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 resultstest(undefined); // unknowntest({ }); // unknowntest({ name: 'apple', color: 'red' }); // apple

  看上面這個例子,我們想列印 fruit 物件中可能存在的 name 屬性。否則我們將列印unknown。我們可以通過預設引數以及解構從而避免判斷條件 fruit && fruit.name

  // 解構 - 僅僅獲取 name 屬性// 為其賦預設值為空物件function test({name} = {}) { console.log (name || 'unknown');}// test resultstest(undefined); // unknowntest({ }); // unknowntest({ 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 resultstest(undefined); // unknowntest({ }); // unknowntest({ name: 'apple', color: 'red' }); // apple

  你可以在jsbin執行demo程式碼。除此之外,如果你是函數語言程式設計的粉絲,你可能選擇使用 Lodash fp,Lodash的函式式版本(方法變更為get或者getOr)。

  4、傾向於物件遍歷而不是Switch語句

  讓我們看下面這個例子,我們想根據 color 打印出水果:

  function test(color) { // 使用條件語句來尋找對應顏色的水果 switch (color) { case 'red': return ['apple', 'strawberry']; case 'yellow': return ['banana', 'pineapple']; case 'purple': return ['grape', 'plum']; default: return []; }}// test resultstest(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 語句對比物件遍歷的更深入的文章,你可以在這個地方閱讀

  TL;DR; 重構語法

  在上面的例子,我們能夠用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 種。

  5、對 所有/部分 判斷使用Array.every & Array.some

  這最後一個建議更多是關於利用 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}

  6、總結

  讓我們一起生產更多可讀性高的程式碼。我希望你能從這篇文章學到東西。

  這就是所有的內容。編碼快樂!