让你更好的编写 JavaScript(ES6) 中条件语句的技巧

1、使用 Array.includes 来处理多个条件 

一般:

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

优化: 

function test(fruit) {
  // 条件提取到数组中
  const redFruits = ['apple', 'strawberry', 'cherry', 'cranberries'];

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

2.选择 Map / Object 字面量,而不是Switch语句

一般:

function test(color) {
  // 使用 switch case 语句,根据颜色找出对应的水果
  switch (color) {
    case 'red':
      return ['apple', 'strawberry'];
    case 'yellow':
      return ['banana', 'pineapple'];
    case 'purple':
      return ['grape', 'plum'];
    default:
      return [];
  }
}

//测试结果
test(null); // []
test('yellow'); // ['banana', 'pineapple']

优化:

// 使用对象字面量,根据颜色找出对应的水果
  const fruitColor = {
    red: ['apple', 'strawberry'],
    yellow: ['banana', 'pineapple'],
    purple: ['grape', 'plum']
  };

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

或者,您可以使用 Map 来实现相同的结果:

// 使用 Map ,根据颜色找出对应的水果
  const fruitColor = new Map()
    .set('red', ['apple', 'strawberry'])
    .set('yellow', ['banana', 'pineapple'])
    .set('purple', ['grape', 'plum']);

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

参考:https://mp.weixin.qq.com/s/T6QWwA1v7GfnBTrgynsfzA

猜你喜欢

转载自blog.csdn.net/baidu_39043816/article/details/108403987