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

寫好JavaScript條件語句的5條守則

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

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

  if (redFruits.includes(fruit)) {  //if (fruit == 'apple' || fruit == 'strawberry') {
    console.log('red');   
  } 
}

2.更少的巢狀,儘早 Return

/_ 當發現無效語句時,儘早Return _/

function
test(fruit, quantity) { const redFruits = ['apple', 'strawberry', 'cherry', 'cranberries']; // 條件 1: 儘早丟擲錯誤 if (!fruit) throw new Error('No fruit!'); // 條件 2: 當fruit不是apple時停止繼續執行 if (!redFruits.includes(fruit)) return; console.log('red'); // 條件 3: 必須是大質量的 if (quantity > 10) { console.log(
'big quantity'); } } // 測試結果 test(null); // error: No fruits test('apple'); // print: red test('apple', 20); // print: red, big quantity

3.使用預設引數和解構

預設值:

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是一個object

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

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

這是一個使用Lodash的例子:

function test(fruit) {
  // 獲取屬性名,如果屬性名不可用,賦預設值為 unknown
  console.log(__.get(fruit, 'name', 'unknown'); 
}

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

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

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) || [];
}

5.重構語法:

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);
}
test('red');   //[{ name: 'apple', color: 'red' },{ name: 'strawberry', color: 'red' }]

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

檢查是否所有水果都是紅色:

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');
  }
    return isAllRed;
}

 test() ;  // 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');

    return isAllRed;
}
test();  // false  

想測試是否存在紅色的水果:

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

function test() {
  // 條件:任何一個水果是紅色
  const isAnyRed = fruits.some(f => f.color == 'red');
    
    return isAnyRed;
}

  test();  // true