不用 if else,如何优雅处理 JavaScript 条件判断?
|
admin
2025年2月21日 14:35
本文热度 309
|
如果使用传统的 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. && 和 || 运算符巧用

5. Switch 模式匹配

6. 使用 Proxy 进行条件拦截

7. 函数式编程方法

8. 状态机模式

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() {
// 编辑文档
}
}
该文章在 2025/2/21 14:36:55 编辑过