JavaScript优化if-else复杂判断问题的常用方案
作者:DEMO派
文章总结了八种常用代码优化模式,包括提前返回、卫语句、策略模式、查表法、多态、责任链模式、可选链和空值合并,并建议根据具体业务场景选择合适的优化方案,优先使用简单方案,保持一致性,考虑可读性,适度抽象,并进行充分测试,需要的朋友可以参考下
一、常用方案
1.1 提前返回(Early Return)
// 优化前
function processOrder(order) {
if (order) {
if (order.status === 'pending') {
if (order.items.length > 0) {
// 处理逻辑
return calculateTotal(order);
} else {
throw new Error('订单无商品');
}
} else {
throw new Error('订单状态无效');
}
} else {
throw new Error('订单不存在');
}
}
// 优化后
function processOrder(order) {
if (!order) throw new Error('订单不存在');
if (order.status !== 'pending') throw new Error('订单状态无效');
if (order.items.length === 0) throw new Error('订单无商品');
return calculateTotal(order);
}
优点:减少嵌套层级,代码清晰易读
缺点:不适合所有场景,特别是需要处理多种成功路径时
1.2 卫语句(Guard Clauses)
// 优化前
function getUserAccess(user) {
if (user) {
if (user.active) {
if (user.role === 'admin') {
return 'full-access';
} else if (user.role === 'editor') {
return 'edit-access';
} else {
return 'read-only';
}
} else {
return 'no-access';
}
} else {
return 'guest-access';
}
}
// 优化后
function getUserAccess(user) {
if (!user) return 'guest-access';
if (!user.active) return 'no-access';
const roleMap = {
'admin': 'full-access',
'editor': 'edit-access',
'default': 'read-only'
};
return roleMap[user.role] || roleMap.default;
}
优点:提前处理异常情况,主逻辑清晰
缺点:多个 return 语句可能影响可读性
1.3 策略模式(Strategy Pattern)
// 优化前
function calculatePrice(userType, price) {
if (userType === 'vip') {
return price * 0.7;
} else if (userType === 'member') {
return price * 0.8;
} else if (userType === 'new') {
return price * 0.9;
} else {
return price;
}
}
// 优化后
const priceStrategies = {
vip: (price) => price * 0.7,
member: (price) => price * 0.8,
new: (price) => price * 0.9,
default: (price) => price
};
function calculatePrice(userType, price) {
const strategy = priceStrategies[userType] || priceStrategies.default;
return strategy(price);
}
// 更灵活的策略模式
class PriceStrategy {
static strategies = {
vip: new VipStrategy(),
member: new MemberStrategy(),
new: new NewUserStrategy(),
default: new DefaultStrategy()
};
static getStrategy(userType) {
return this.strategies[userType] || this.strategies.default;
}
}
优点:易于扩展,符合开闭原则
缺点:增加复杂度,简单场景可能过度设计
1.4 查表法/映射表(Lookup Table)
// 优化前
function getStatusText(status) {
if (status === 1) {
return '待支付';
} else if (status === 2) {
return '已支付';
} else if (status === 3) {
return '发货中';
} else if (status === 4) {
return '已完成';
} else if (status === 5) {
return '已取消';
} else {
return '未知状态';
}
}
// 优化后
const STATUS_MAP = {
1: '待支付',
2: '已支付',
3: '发货中',
4: '已完成',
5: '已取消'
};
function getStatusText(status) {
return STATUS_MAP[status] || '未知状态';
}
// 更复杂的数据结构
const STATUS_CONFIG = {
1: { text: '待支付', color: 'orange', action: 'pay' },
2: { text: '已支付', color: 'blue', action: 'view' },
3: { text: '发货中', color: 'green', action: 'track' },
4: { text: '已完成', color: 'gray', action: 'review' }
};
优点:代码简洁,易于维护和扩展
缺点:不适用于复杂条件逻辑
1.5 多态/状态模式(Polymorphism/State Pattern)
// 优化前
class Order {
process() {
if (this.status === 'pending') {
// 待处理逻辑
} else if (this.status === 'paid') {
// 已支付逻辑
} else if (this.status === 'shipped') {
// 已发货逻辑
}
}
}
// 优化后
class OrderState {
process(order) {
throw new Error('必须实现 process 方法');
}
}
class PendingState extends OrderState {
process(order) {
console.log('处理待支付订单');
// 具体逻辑
}
}
class PaidState extends OrderState {
process(order) {
console.log('处理已支付订单');
// 具体逻辑
}
}
class Order {
constructor() {
this.state = new PendingState();
}
setState(state) {
this.state = state;
}
process() {
return this.state.process(this);
}
}
优点:封装状态行为,易于添加新状态
缺点:增加类数量,简单场景可能过度设计
1.6 责任链模式(Chain of Responsibility)
// 优化前
function handleRequest(type, data) {
if (type === 'typeA') {
return handleTypeA(data);
} else if (type === 'typeB') {
return handleTypeB(data);
} else if (type === 'typeC') {
return handleTypeC(data);
} else {
return handleDefault(data);
}
}
// 优化后
class Handler {
constructor() {
this.nextHandler = null;
}
setNext(handler) {
this.nextHandler = handler;
return handler;
}
handle(type, data) {
if (this.nextHandler) {
return this.nextHandler.handle(type, data);
}
return null;
}
}
class TypeAHandler extends Handler {
handle(type, data) {
if (type === 'typeA') {
return `处理 typeA: ${data}`;
}
return super.handle(type, data);
}
}
// 使用
const handlerChain = new TypeAHandler()
.setNext(new TypeBHandler())
.setNext(new TypeCHandler())
.setNext(new DefaultHandler());
优点:解耦发送者和接收者,灵活组合
缺点:可能影响性能,调试复杂
1.7 可选链(Optional Chaining)和空值合并(Nullish Coalescing)
// 优化前
function getUserInfo(user) {
if (user && user.profile && user.profile.contact && user.profile.contact.email) {
return user.profile.contact.email;
} else {
return 'default@email.com';
}
}
// 优化后
function getUserInfo(user) {
return user?.profile?.contact?.email ?? 'default@email.com';
}
// 配合默认参数
function processConfig(config = {}) {
const {
timeout = 5000,
retry = 3,
logLevel = 'info'
} = config;
// 使用配置
}
优点:语法简洁,减少空值检查
缺点:ES2020+ 特性,需要环境支持
二、建议与总结
选择建议:
- 简单条件判断 → 使用提前返回、卫语句、可选链操作符
- 状态/类型映射 → 使用查表法
- 复杂业务逻辑 → 使用策略模式、状态模式
- 请求/事件处理链 → 使用责任链模式
最佳实践总结:
- 优先使用简单方案:不要为简单问题引入复杂模式
- 保持一致性:在项目中保持统一的代码风格
- 考虑可读性:优化不仅要减少嵌套,还要提高代码可读性
- 适度抽象:避免过度设计,根据实际需求选择模式
- 测试覆盖:复杂逻辑需要充分的测试覆盖
根据具体的业务场景和团队习惯选择合适的优化方案。简单的 if-else 嵌套不一定需要优化,只有当它影响到代码的可读性、可维护性或可扩展性时才考虑重构。始终以代码清晰和易于维护为目标。
以上就是JavaScript优化if-else复杂判断问题的常用方案的详细内容,更多关于JavaScript优化if-else复杂判断的资料请关注脚本之家其它相关文章!
