1. 程式人生 > >JavaScript的5個技巧幫助你寫出更好的條件語句

JavaScript的5個技巧幫助你寫出更好的條件語句

使用JavaScript時,我們會遇到很多的條件語句,這裡有5個技巧能幫助你寫出更好/簡潔的條件語句。

  1. 對多個條件使用Array.includes
  2. 更少巢狀,儘早return
  3. 使用預設的函式引數和解構
  4. 支援Map / Object 語法而不是Switch語句
  5. 對所有/部分標準使用Array.every和Array.some
  6. 總結

1. 對多個條件使用Array.includes

先看看下面的例子:

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

乍看上去,上面的例子似乎還不錯。然而,如果我們有更多的紅色水果,例如 cherrycranberries 呢?我們要用更多的 || 擴充套件語句嗎?

我們可以用 Array.includes(Array.includes) 重寫上面的條件語句。

function test(fruit) {
  // extract conditions to array
  const redFruits = ['apple', 'strawberry', 'cherry', 'cranberries'];

  if (redFruits.includes(fruit)) {
    console.log('red');
  }
}

通過提取 red fruits 為一個數組,使得程式碼看起來更整潔了。

2.更少巢狀,儘早return

將上面的例子擴充套件到再包含兩個條件語句:

  • 如果沒提供fruit,丟擲錯誤
  • 接收 fruit 的 quantity, 並在大於10時列印
function test(fruit, quantity) {
  const redFruits = ['apple', 'strawberry', 'cherry', 'cranberries'];

  // 第一個條件語句: fruit 有值
  if (fruit) {
    // 第二個條件語句: 是紅的
    if (redFruits.includes(fruit)) {
      console.log('red');

      // 第三個條件語句: 質量大
      if (quantity > 10) {
        console.log('big quantity');
      }
    }
  } else {
    throw new Error('No fruit!');
  }
}

// test results
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 early when invalid conditions found _/

function test(fruit, quantity) {
  const redFruits = ['apple', 'strawberry', 'cherry', 'cranberries'];

  // 第一個條件語句: 更早丟擲錯誤
  if (!fruit) throw new Error('No fruit!');

  // 第二個條件語句: 是紅的
  if (redFruits.includes(fruit)) {
    console.log('red');

    // 第三個條件語句: 質量大
    if (quantity > 10) {
      console.log('big quantity');
    }
  }
}

這樣做,程式碼就能減少一層巢狀。這種編碼風格很棒,特別是對長長的if語句來說(想象你滑到最底部了才知道還有一個else語句,一點都不cool)。

我們還可以進一步減少if的巢狀,通過轉換條件和儘早return。觀察下面的第二個條件語句:

/_ return early when invalid conditions found _/

function test(fruit, quantity) {
  const redFruits = ['apple', 'strawberry', 'cherry', 'cranberries'];

  if (!fruit) throw new Error('No fruit!'); // 第一個條件語句: 更早丟擲錯誤
  if (!redFruits.includes(fruit)) return; // 第二個條件語句: fruit 不是紅的就結束

  console.log('red');

  // 第三個條件語句: 質量大
  if (quantity > 10) {
    console.log('big quantity');
  }
}

通過轉換第二個條件語句的判斷,現在程式碼擺脫了巢狀。當代碼有很長的邏輯時,這種技術非常有用,我們希望在條件不滿足時停止進一步的處理。

然而,這裡沒有什麼硬性規定。自我評估一下,這個版本(沒有巢狀)相比前面那個版本(巢狀第二個條件語句)更好/更可讀嗎?

對於我個人而言,我會在前面那個版本(巢狀第二個條件語句)時就放過它。這是因為:

  • 程式碼更簡短和直觀,if巢狀使得程式碼更清晰
  • 轉換條件語句可能會導致更多思考過程(增加認知負荷)

因此,通常旨在減少巢狀和儘早Return,但不要矯枉過正。如果你有興趣深入討論這個話題,這裡有一篇文章和StackOverflow帖子:

3. 使用預設的函式引數和解構

我猜你會覺得下面的程式碼很眼熟,在使用JavaScript時,我們總是需要檢測 null/undefined 值和分配預設值:

function test(fruit, quantity) {
  if (!fruit) return;
  const q = quantity || 1; // 如果quantity沒有值, 預設分配一個

  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沒有值, 預設分配一個
  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 = 'unknow', quantity = 1).

那如果 fruit 是一個物件呢?還能分配預設引數嗎?

function test(fruit) { 
  // 如果 fruit name 有值就將其打印出來
  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 有值,就將其打印出來;否則列印 unknow 。可以用預設函式引數和解構來避免條件語句 fruit && fruit.name 的檢測。

// 解構 - 僅獲取 name 屬性
// 分配預設空物件 {}
function test({name} = {}) {
  console.log (name || 'unknown');
}

//test results
test(undefined); // unknown
test({ }); // unknown
test({ name: 'apple', color: 'red' }); // apple

因為我們只需要fruit的name屬性,我們可以使用{name}解構引數,然後我們可以用 name 作為程式碼中變數替代fruit.name.

我們還分配預設空物件 {} 作為預設值。如果我們不這麼做,在執行到 test(undefined)這行時就會報錯Cannot destructure property name of 'undefined' or 'null'.因為undefined沒有 name 屬性。

如果你不介意使用第三方庫,這裡還有一些辦法免去空值檢測:

  • 使用 Lodash get 函式
  • 使用Facebook開源的 idx 庫

這裡是一個使用Lodash的示例:

// Include lodash library, you will get _
function test(fruit) {
  console.log(__.get(fruit, 'name', 'unknown'); // get property name, if not available, assign default value 'unknown'
}

//test results
test(undefined); // unknown
test({ }); // unknown
test({ name: 'apple', color: 'red' }); // apple

4. 支援Map / Object 語法而不是Switch語句

看下面的示例,我們想通過color列印fruit:

function test(color) {
  // use switch case to find fruits in 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']

上面的程式碼看起來沒什麼異常,但我覺得它太囉嗦了。使用更清晰的物件語法也能實現同樣的效果:

// use object literal to find fruits in color
  const fruitColor = {
    red: ['apple', 'strawberry'],
    yellow: ['banana', 'pineapple'],
    purple: ['grape', 'plum']
  };

function test(color) {
  return fruitColor[color] || [];
}

或者,你還可以使用 Map 來實現同樣的效果:

// use Map to find fruits in color
  const fruitColor = new Map()
    .set('red', ['apple', 'strawberry'])
    .set('yellow', ['banana', 'pineapple'])
    .set('purple', ['grape', 'plum']);

function test(color) {
  return fruitColor.get(color) || [];
}

從ES2015之後,Map就是物件型別了,允許你儲存鍵值對。

*應該禁止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) {
  // use Array filter to find fruits in color

  return fruits.filter(f => f.color == color);
}

總是有更多的辦法來實現同樣的效果。我們對於同一個例子已經展示4中辦法了。程式碼樂趣多!

5. 對所有/部分標準使用Array.every和Array.some

最後一個技巧是更多地關於利用新(但也不是那麼新)的JavaScript陣列函式來減少程式碼行數。觀察下面的程式碼,我們想檢測是否所有fruit都是red顏色的:

const fruits = [
    { name: 'apple', color: 'red' },
    { name: 'banana', color: 'yellow' },
    { name: 'grape', color: 'purple' }
  ];

function test() {
  let isAllRed = true;

  // condition: all fruits must be red
  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() {
  // condition: short way, all fruits must be red
  const isAllRed = fruits.every(f => f.color == 'red');

  console.log(isAllRed); // false
}

更清晰了不是嗎?如果我們想檢測fruit中是否有任何red顏色的,我們可以用一行Array.some來實現。

const fruits = [
    { name: 'apple', color: 'red' },
    { name: 'banana', color: 'yellow' },
    { name: 'grape', color: 'purple' }
];

function test() {
  // condition: if any fruit is red
  const isAnyRed = fruits.some(f => f.color == 'red');

  console.log(isAnyRed); // true
}

6. 總結

讓我們一起生產更多可讀的程式碼吧。我希望你在這篇文章中有所收穫。
以上。享受程式設計!