【譯】JavaScript 中寫好條件語句的五個技巧

banner

當用JavaScript來工做的時候,咱們須要處理不少的條件判斷,這裏有五個小技巧能幫助你寫出更好/更清晰的條件語句。javascript

1. 多重判斷中使用Array.includesjava

咱們看下下面這個例子:git

// condition
function test(fruit) {
  if (fruit == 'apple' || fruit == 'strawberry') {
    console.log('red');
  }
}
複製代碼

乍一看,上面的例子看起來還能夠哦。可是,若是添加更多的紅色的水果,好比cherrycranberries,那會怎樣呢?你會使用更多的||來擴展條件語句嗎?github

咱們能夠經過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. 少嵌套,早返回babel

咱們擴展上面的例子,讓它包含多兩個條件:app

  • 若是沒有傳入fruit參數,拋出錯誤
  • 接受quantity參數並在其超出10打印出來
function test(fruit, quantity) {
  const redFruits = ['apple', 'strawberry', 'cherry', 'cranberries'];

  // condition 1: fruit must has value
  if (fruit) {
    // condition 2: must be red
    if (redFruits.includes(fruit)) {
      console.log('red');

      // condition 3: must be big quantity
      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
複製代碼

看下上面的代碼,咱們捋下:ide

  • 1個if/else語句篩出無效的條件語句
  • 3層嵌套的語句(條件1,2和3)

我我的遵照的準則是發現無效的條件時,及早return函數式編程

/_ return early when invalid conditions found _/

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

  // condition 1: throw error early
  if (!fruit) throw new Error('No fruit!');

  // condition 2: must be red
  if (redFruits.includes(fruit)) {
    console.log('red');

    // condition 3: must be big quantity
    if (quantity > 10) {
      console.log('big quantity');
    }
  }
}
複製代碼

經過及早return,咱們減小了一層嵌套語句。這種編碼風格很贊,尤爲是當你有很長的if語句(能夠想象下你須要滾動很長才知道有else語句,一點都不酷)。

(針對上面例子)咱們能夠經過倒置判斷條件和及早return來進一步減小if嵌套。看下面咱們是怎麼處理條件2的:

/_ return early when invalid conditions found _/

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

  if (!fruit) throw new Error('No fruit!'); // condition 1: throw error early
  if (!redFruits.includes(fruit)) return; // condition 2: stop when fruit is not red

  console.log('red');

  // condition 3: must be big quantity
  if (quantity > 10) {
    console.log('big quantity');
  }
}
複製代碼

經過倒置條件2,咱們避免了嵌套語句。這個技巧頗有用:當咱們處理很長的邏輯,而且但願可以在條件不知足時可以停下來進行處理。

並且,這樣作並不難。問下本身,這個版本(沒有條件嵌套)是否是比以前版本(兩層嵌套)更好/可讀性更高呢?

可是,對於我來講,我會保留先前的版本(包含兩層嵌套)。由於:

  • 代碼較短且直接,嵌套if更加清晰
  • 倒置判斷條件可能增長思考負擔(增長認知負荷)

所以,應當儘可能減小嵌套和及早return,可是不要過分。若是你感興趣,你能夠看下面的一篇文章和StackOverflow上的討論,進一步瞭解:

3. 使用默認參數和解構

我猜你對下面的代碼有些熟悉,在JavaScript中咱們總須要檢查null/undefined值和指定默認值。

function test(fruit, quantity) {
  if (!fruit) return;
  const q = quantity || 1; // if quantity not provided, default to one

  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) { // if quantity not provided, default to one
  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是一個對象會怎樣呢?咱們能分配一個默認參數嗎?

function test(fruit) { 
  // printing fruit name if value provided
  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

// destructing - get name property only
// assign default empty object {}
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了。

咱們也聲明瞭一個空對象{}做爲默認值。若是咱們沒有這麼作,你會獲得一個沒法對undefined或null解構的錯誤。由於在undefined中沒有name屬性。

若是你不介意使用第三方庫,有一些方式能減小null的檢查:

  • 使用 Lodash get 函數
  • 臉書的開源庫idx(配合babeljs使用)

這有一個使用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
複製代碼

你能夠在JSBIN這裏運行demo代碼,若是你是函數式編程的粉絲,你能夠選擇Lodash fp,Lodash的函數式版本(方法變動爲get或者getOr)。

4. 傾向對象遍歷而不是switch語句

看下下面的代碼,咱們想基於color來打印水果。

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']
複製代碼

上面的代碼看似沒問題,可是多少有些冗餘。用遍歷對象(object literal)來實現相同的結果,語法看起來更加簡潔:

// 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) || [];
}
複製代碼

Map是ES2015規範以後實現的對象類型,容許你存儲鍵值對。

那麼,咱們應該禁止使用switch語句嗎?不要限制本身作這個。我的來講,我會盡量使用對象遍歷,可是不會嚴格遵照它,而是使用對當前場景更有意義的方式。

Todd Motto 有篇對switch語句和遍歷對象深層次對比的文章,你能夠戳這裏來查看。

TL;DL;重構語法

針對上面的例子,咱們能夠經過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的內置數組函數來減小代碼的行數。看下下面的代碼,咱們想查看全部的水果是不是紅色:

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
}
複製代碼

更清晰了,對吧?相似的,咱們想測試是否有水果是紅色的,咱們可使用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
}
複製代碼

總結

讓咱們一塊兒寫出可讀性更高的代碼。我但願你能從這篇文章學到些新東西。

這是所有內容。祝你編碼愉快!

原文 scotch.io/bar-talk/5-…

文章首發:github.com/reng99/blog…

更多內容:github.com/reng99/blog…

相關文章
相關標籤/搜索