如果使用传统的 if-else 语句,对复杂的条件进行逻辑判断,代码很容易变得冗长难维护,分享几种替代的写法。
1. 对象映射替代 if-else
传统写法
function getPrice(user) {
if (user.type === 'vip') {
return 'VIP价格';
} else if (user.type === 'svip') {
return 'SVIP价格';
} else if (user.type === 'vvip') {
return 'VVIP价格';
} else {
return '普通价格';
}
}
替代写法
const priceStrategy = {
vip: () => 'VIP价格',
svip: () => 'SVIP价格',
vvip: () => 'VVIP价格',
default: () => '普通价格'
};
function getPrice(user) {
return (priceStrategy[user.type] || priceStrategy.default)();
}
2. Array.includes 替代多条件
传统写法
if (status === 'failed' || status === 'error' || status === 'rejected') {
handleError();
}
替代写法
const errorStatus = ['failed', 'error', 'rejected'];
if (errorStatus.includes(status)) {
handleError();
}
3. 三元运算符链式使用
传统写法
let message;
if (score >= 90) {
message = '优秀';
} else if (score >= 80) {
message = '良好';
} else if {score >= 60} {
message = '及格';
} else {
message = '不及格';
}
替代写法
const message =
score >= 90 ? '优秀':
score >= 80 ? '良好':
score >= 60 ? '及格':'不及格';
4. && 和 || 运算符巧用
// 替代简单if
user.isAdmin && showAdminPanel();
// 设置默认值
const name =user.name || 'unnamed';
// 空值合并运算符
const count=data?.users ?? [];
5. Switch 模式匹配
const actions= new Map([
[/^vip/, handleVip],
[/^admin/, handleAdmin],
[/^user/, handleUser]
]);
const handleRequest = (type) => {
const action = [...actions].find(([key]) => key.test(type));
return action ? action[1]() : handleDefault();
}
6. 使用 Proxy 进行条件拦截
const handler = {
get: (target,property) => {
return property in target ?
target[property] :
target.default;
}
};
const services = new Proxy('
admin:()=> 'Admin Service',
user:()=> 'User Service,
default:()=> 'Default Service'
}, handler);
7. 函数式编程方法
// 组合条件
const isAdult = age => age >= 18;
const hasPermission = role => ['admin','superuser'].includes(role);
const canAccess = user => isAdult(user.age) && hasPermission(user.role);
// 使用
users.filter(canAccess).forEach(grantAccess);
8. 状态机模式
const stateMachine = {
draft:{
publish:'published',
delete:'deleted'
},
published:{
unpublish:'draft',
archive:'archived'
},
archived:{
restore:'draft'
}
};
const changeState = (currentState,action) => stateMachine[currentState]?.[action] || currentState;
9. 使用装饰器处理条件
function checkPermission(target, name, descriptor) {
const original = descriptor.value;
descriptor.value = function(...args) {
if (this.user?.hasPermission) {
return original.apply(this, args);
}
throw new Error('No permission');
};
return descriptor;
}
class Document {
@checkPermission
edit() {
// 编辑文档
}
}