前言:避免滥用控制语句,应该尽量简化代码逻辑,避免出现重复和冗余代码。通过合理的模块化和抽象来简化代码结构。
一、嵌套的代码
不管是if、for、switch、回调等,都应该避免出现多级嵌套
badCase:
function fn1(a) {
setTimeout(() => {
console.log(a);
a--;
setTimeout(() => {
console.log(a);
a--
setTimeout(() => {
console.log(a);
a--
setTimeout(() => {
console.log(a);
a--
setTimeout(() => {
console.log(a);
}, 1000);
}, 1000);
}, 1000);
}, 1000);
}, 1000);
}
fn1(5)
goodCase:
function fn1(a) {
new Promise((res,rej)=>{
res(a)
})
.then((params)=>{
return new Promise((res,rej)=>{
setTimeout(() => { console.log(params);res(--params) }, 1000) })
})
.then((params)=>{
return new Promise((res,rej)=>{
setTimeout(() => { console.log(params);res(--params) }, 1000) })
})
.then((params)=>{
return new Promise((res,rej)=>{
setTimeout(() => { console.log(params);res(--params) }, 1000) })
})
.then((params)=>{
return new Promise((res,rej)=>{
setTimeout(() => { console.log(params);res(--params) }, 1000) })
})
.then((params)=>{
return new Promise((res,rej)=>{
setTimeout(() => { console.log(params);res(--params) }, 1000) })
})
}
let a=5
fn1(a)
二、if和else(避免使用else)
else会增加块级区域,虽然一时影响不大,但未必后续添加嵌套逻辑。可以使用卫语句取代。
badCase:
if (a > b) {
console.log('a')
} else {
console.log('b')
}
goodCase:
if (a > b) {
console.log('a')
return ;
}
console.log('b')
三、重复的switch
过多的switch会出现大量重复的结构,可以采用对象映射、函数映射、策略模式等。
badCase:
function handleAction(type, data) {
switch (type) {
case 'add':
return addData(data);
case 'delete':
return deleteData(data);
case 'update':
return updateData(data);
// ... 假设这里还有更多的case
default:
throw new Error('Unknown action type');
}
}
// 使用
handleAction('add', { id: 1, value: 'Hello' });
goodCase:
const actionHandlers = {
'add': addData,
'delete': deleteData,
'update': updateData,
// ... 可以轻松添加更多类型
};
function handleAction(type, data) {
const handler = actionHandlers[type];
if (handler) {
return handler(data);
}
throw new Error('Unknown action type');
}
// 使用
handleAction('add', { id: 1, value: 'Hello' });
四、使用es6代替for语句
很多场景都需要循环去加工或处理一些数据,使用循环是必不可免的,使用es6可以减少结构的嵌套,并且支持链式调用。
badCase:
let people = [
{ name: 'Alice', age: 25 },
{ name: 'Bob', age: 17 },
{ name: 'Charlie', age: 22 },
{ name: 'David', age: 15 }
];
let adults = [];
for (let i = 0; i < people.length; i++) {
if (people[i].age > 18) {
adults.push(people[i]);
}
}
console.log(adults);
goodCase:
let people = [
{ name: 'Alice', age: 25 },
{ name: 'Bob', age: 17 },
{ name: 'Charlie', age: 22 },
{ name: 'David', age: 15 }
];
let adults = people.filter(person => person.age > 18);
console.log(adults);