1、尽量别用“非”条件句
// Bad:
function isDOMNodeNotPresent(node) {
// ...
}
if (!isDOMNodeNotPresent(node)) {
// ...
}
// Good:
function isDOMNodePresent(node) {
// ...
}
if (isDOMNodePresent(node)) {
// ...
}
2、对于多个条件,使用 Array.includes
// Bad
const checkCarModel = (model) => {
if(model === 'renault' || model === 'peugeot') {
console.log('model valid');
}
}
checkCarModel('renault'); // 输出 'model valid'
// Good
const checkCarModel = (model) => {
const models = ['peugeot', 'renault'];
if(models.includes(model)) {
console.log('model valid');
}
}
checkCarModel('renault'); // 输出 'model valid'
3、传参使用默认值
function createMicrobrewery(name = 'Hipster Brew Co.') {
console.log(name);
}
createMicrobrewery('lzq');
4、使用索引或者映射,而不是 switch 语句
1)正常的switch语句
const getCarsByState = (state) => {
switch (state) {
case 'usa':
return ['Ford', 'Dodge'];
case 'france':
return ['Renault', 'Peugeot'];
case 'italy':
return ['Fiat'];
default:
return [];
}
}
console.log(getCarsByState()); // 输出 []
console.log(getCarsByState('usa')); // 输出 ['Ford', 'Dodge']
console.log(getCarsByState('italy')); // 输出 ['Fiat']
2)重构,使用new Map()语句
const cars = new Map()
.set('usa', ['Ford', 'Dodge'])
.set('france', ['Renault', 'Peugeot'])
.set('italy', ['Fiat']);
const getCarsByState = (state) => {
return cars.get(state) || [];
}
console.log(getCarsByState()); // 输出 []
console.log(getCarsByState('usa')); //输出 ['Ford', 'Dodge']
console.log(getCarsByState('italy')); // 输出 ['Fiat']
3)使用对象
const carState = {
usa: ['Ford', 'Dodge'],
france: ['Renault', 'Peugeot'],
italy: ['Fiat']
};
const getCarsByState = (state) => {
return carState[state] || [];
}
console.log(getCarsByState()); // 输出 []
console.log(getCarsByState('usa')); // 输出 ['Ford', 'Dodge']
console.log(getCarsByState('france')); // 输出 ['Renault', 'Peugeot']