1、条件判断Array.includes()
这是业务中最常见的情景之一
看代码:
function isOk(color) {
if(color=== 'red' || color === 'yellow') {
return true;
}else {
return false;
}
}
一个简单的条件判断,如果判断条件较少时,比如一两个还好,如果很多的时候就会写很长的条件判断,if(、、|| 、、||、、||、、||、、、、、、)
优化:
function isOk(color) {
let colorArr = ['red','yellow'];
if(colorArr.includs(color)) {
return true;
}else {
return false;
}
}
这样不管有多少判断条件,只需要把条件添加到数组中去就行。
2、Early exit / Return early
尽早的返回或跳出不符合条件的状态,避免不必要的开销,不要走些没用的过场
看代码:
const printDetail = animal => {
if (animal) {
if (animal.type) {
if (animal.name) {
if (animal.weight) {
console.log(
`${animal.type}+${animal.name}+${animal.weight}`
);
} else {
console.log('no weight');
}
} else {
console.log('no name');
}
} else {
console.log('no type');
}
} else {
console.log('null');
}
};
printDetail(); // null
printDetail({}); // no type
printDetail({type: 'dog'}); // no name
printDetail({type: 'dog',name:'jiji'}); // no weight
printDetail({type: 'dog',name:'jiji',weight:'12kg'}); // dog+jiji+12kg
这个函数嵌套太多层了,虽然可以很好的工作,但是可读性差,不便于维护,一不小心少了个括号就会报错,很难找到原因
简化
const printDetail = ({ type, name, weight } = {}) => {
if (!animal.type) {
console.log('no type');
return;
}
if (!animal.name) {
console.log('no name');
return;
}
if (!animal.weight) {
console.log('no weight');
return;
}
console.log(`${animal.type}+${animal.name}+${animal.weight}`);
};
printDetail(); // no type
printDetail({ type: 'dog' }); // no name
printDetail({ type: 'dog', name: 'jiji' }); // no weight
printDetail({ type: 'dog', name: 'jiji', weight: '12kg' }); // dog+jiji+12kg
再看一个案例:
function printVegetablesWithQuantity(vegetable, quantity) {
const vegetables = [
'potato',
'cabbage',
'cauliflower',
'asparagus'
];
if (vegetable) {
if (vegetables.includes(vegetable)) {
console.log(`I like ${vegetable}`);
if (quantity >= 10) {
console.log('hahahaha');
}
}
} else {
throw new Error('error!');
}
}
printVegetablesWithQuantity(null); // error!
printVegetablesWithQuantity('cabbage'); // I like cabbage
printVegetablesWithQuantity('cabbage', 20); // 'I like cabbage`
// hahahaha
这段代码嵌套了三层,可以做一些优化,减少嵌套和复杂度。
function printVegetablesWithQuantity(vegetable, quantity) {
const vegetables = [
'potato',
'cabbage',
'cauliflower',
'asparagus'
];
if (!vegetable) throw new Error('error!');
if (!vegetables.includes(vegetable)) return;
console.log(`I like ${vegetable}`);
if (quantity >= 10) {
console.log('hahahaha');
}
}
printVegetablesWithQuantity(null); // error!
printVegetablesWithQuantity('cabbage'); // I like cabbage
printVegetablesWithQuantity('cabbage', 20); // 'I like cabbage`
// hahahaha
是不是简洁了很多!
3、Object Literal or Map instead of Switch Statement
用对象索引或者map替代switch函数
看案例:
function printFruits(color) {
switch (color) {
case 'red':
return ['apple'];
case 'yellow':
return ['banana'];
case 'purple':
return ['grape'];
default:
return [];
}
}
printFruits(null); // []
printFruits('yellow'); // ['banana']
switch虽然比if else简洁了许多,但遇到情况很多的时候还是略显冗余
使用对象索引优化:
function printVegetablesWithQuantity(color) {
const fruitMap = {
red: ['apple'],
yellow: ['banana'],
purple: ['plum']
};
return fruitMap[color] || [];
}
map方法优化:
function printVegetablesWithQuantity(color) {
const fruitMap = new Map()
.set('red', ['apple'])
.set('yellow', ['banana'])
.set('purple', ['plum']);
return fruitMap.get(color) || [];
}
个人觉得map方法没有对象索引简洁、直观,更喜欢对象索引方法。