1. Use Array.includes to handle multiple conditions
general:
// condition
function test(fruit) {
if (fruit == 'apple' || fruit == 'strawberry') {
console.log('red');
}
}
optimization:
function test(fruit) {
// 条件提取到数组中
const redFruits = ['apple', 'strawberry', 'cherry', 'cranberries'];
if (redFruits.includes(fruit)) {
console.log('red');
}
}
2. Choose Map / Object literal instead of Switch statement
general:
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']
optimization:
// 使用对象字面量,根据颜色找出对应的水果
const fruitColor = {
red: ['apple', 'strawberry'],
yellow: ['banana', 'pineapple'],
purple: ['grape', 'plum']
};
function test(color) {
return fruitColor[color] || [];
}
Alternatively, you can use Map to achieve the same result:
// 使用 Map ,根据颜色找出对应的水果
const fruitColor = new Map()
.set('red', ['apple', 'strawberry'])
.set('yellow', ['banana', 'pineapple'])
.set('purple', ['grape', 'plum']);
function test(color) {
return fruitColor.get(color) || [];
}
Reference: https://mp.weixin.qq.com/s/T6QWwA1v7GfnBTrgynsfzA