不用 if else,如何优雅处理 JavaScript 条件判断?
|
admin
2025年10月16日 19:34
本文热度 211
|
如果使用传统的 if-else 语句,对复杂的条件进行逻辑判断,代码很容易变得冗长难维护,分享几种替代的写法。
1. 对象映射替代 if-else
传统写法
functiongetPrice(user) {
if (user.type === 'vip') {
return'VIP价格';
} elseif (user.type === 'svip') {
return'SVIP价格';
} elseif (user.type === 'vvip') {
return'VVIP价格';
} else {
return'普通价格';
}
}
替代写法
const priceStrategy = {
vip: () => 'VIP价格',
svip: () => 'SVIP价格',
vvip: () => 'VVIP价格',
default: () => '普通价格'
};
functiongetPrice(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. 三元运算符链式使用
传统写法

替代写法

4. && 和 || 运算符巧用

5. Switch 模式匹配

6. 使用 Proxy 进行条件拦截

7. 函数式编程方法

8. 状态机模式

9. 使用装饰器处理条件
functioncheckPermission(target, name, descriptor) {
const original = descriptor.value;
descriptor.value = function(...args) {
if (this.user?.hasPermission) {
return original.apply(this, args);
}
thrownewError('No permission');
};
return descriptor;
}
classDocument {
@checkPermission
edit() {
// 编辑文档
}
}
欢迎补充。
阅读原文:原文链接
该文章在 2025/10/17 17:36:30 编辑过