JavaScript優(yōu)化if-else復雜判斷問題的常用方案
一、常用方案
1.1 提前返回(Early Return)
// 優(yōu)化前
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('訂單狀態(tài)無效');
}
} else {
throw new Error('訂單不存在');
}
}
// 優(yōu)化后
function processOrder(order) {
if (!order) throw new Error('訂單不存在');
if (order.status !== 'pending') throw new Error('訂單狀態(tài)無效');
if (order.items.length === 0) throw new Error('訂單無商品');
return calculateTotal(order);
}
優(yōu)點:減少嵌套層級,代碼清晰易讀
缺點:不適合所有場景,特別是需要處理多種成功路徑時
1.2 衛(wèi)語句(Guard Clauses)
// 優(yōu)化前
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';
}
}
// 優(yōu)化后
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;
}
優(yōu)點:提前處理異常情況,主邏輯清晰
缺點:多個 return 語句可能影響可讀性
1.3 策略模式(Strategy Pattern)
// 優(yōu)化前
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;
}
}
// 優(yōu)化后
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;
}
}
優(yōu)點:易于擴展,符合開閉原則
缺點:增加復雜度,簡單場景可能過度設(shè)計
1.4 查表法/映射表(Lookup Table)
// 優(yōu)化前
function getStatusText(status) {
if (status === 1) {
return '待支付';
} else if (status === 2) {
return '已支付';
} else if (status === 3) {
return '發(fā)貨中';
} else if (status === 4) {
return '已完成';
} else if (status === 5) {
return '已取消';
} else {
return '未知狀態(tài)';
}
}
// 優(yōu)化后
const STATUS_MAP = {
1: '待支付',
2: '已支付',
3: '發(fā)貨中',
4: '已完成',
5: '已取消'
};
function getStatusText(status) {
return STATUS_MAP[status] || '未知狀態(tài)';
}
// 更復雜的數(shù)據(jù)結(jié)構(gòu)
const STATUS_CONFIG = {
1: { text: '待支付', color: 'orange', action: 'pay' },
2: { text: '已支付', color: 'blue', action: 'view' },
3: { text: '發(fā)貨中', color: 'green', action: 'track' },
4: { text: '已完成', color: 'gray', action: 'review' }
};
優(yōu)點:代碼簡潔,易于維護和擴展
缺點:不適用于復雜條件邏輯
1.5 多態(tài)/狀態(tài)模式(Polymorphism/State Pattern)
// 優(yōu)化前
class Order {
process() {
if (this.status === 'pending') {
// 待處理邏輯
} else if (this.status === 'paid') {
// 已支付邏輯
} else if (this.status === 'shipped') {
// 已發(fā)貨邏輯
}
}
}
// 優(yōu)化后
class OrderState {
process(order) {
throw new Error('必須實現(xiàn) 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);
}
}
優(yōu)點:封裝狀態(tài)行為,易于添加新狀態(tài)
缺點:增加類數(shù)量,簡單場景可能過度設(shè)計
1.6 責任鏈模式(Chain of Responsibility)
// 優(yōu)化前
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);
}
}
// 優(yōu)化后
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());
優(yōu)點:解耦發(fā)送者和接收者,靈活組合
缺點:可能影響性能,調(diào)試復雜
1.7 可選鏈(Optional Chaining)和空值合并(Nullish Coalescing)
// 優(yōu)化前
function getUserInfo(user) {
if (user && user.profile && user.profile.contact && user.profile.contact.email) {
return user.profile.contact.email;
} else {
return 'default@email.com';
}
}
// 優(yōu)化后
function getUserInfo(user) {
return user?.profile?.contact?.email ?? 'default@email.com';
}
// 配合默認參數(shù)
function processConfig(config = {}) {
const {
timeout = 5000,
retry = 3,
logLevel = 'info'
} = config;
// 使用配置
}
優(yōu)點:語法簡潔,減少空值檢查
缺點:ES2020+ 特性,需要環(huán)境支持
二、建議與總結(jié)
選擇建議:
- 簡單條件判斷 → 使用提前返回、衛(wèi)語句、可選鏈操作符
- 狀態(tài)/類型映射 → 使用查表法
- 復雜業(yè)務(wù)邏輯 → 使用策略模式、狀態(tài)模式
- 請求/事件處理鏈 → 使用責任鏈模式
最佳實踐總結(jié):
- 優(yōu)先使用簡單方案:不要為簡單問題引入復雜模式
- 保持一致性:在項目中保持統(tǒng)一的代碼風格
- 考慮可讀性:優(yōu)化不僅要減少嵌套,還要提高代碼可讀性
- 適度抽象:避免過度設(shè)計,根據(jù)實際需求選擇模式
- 測試覆蓋:復雜邏輯需要充分的測試覆蓋
根據(jù)具體的業(yè)務(wù)場景和團隊習慣選擇合適的優(yōu)化方案。簡單的 if-else 嵌套不一定需要優(yōu)化,只有當它影響到代碼的可讀性、可維護性或可擴展性時才考慮重構(gòu)。始終以代碼清晰和易于維護為目標。
以上就是JavaScript優(yōu)化if-else復雜判斷問題的常用方案的詳細內(nèi)容,更多關(guān)于JavaScript優(yōu)化if-else復雜判斷的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
JavaScript?對象新增方法defineProperty與keys的使用說明
這篇文章主要介紹了JavaScript對象新增方法defineProperty與keys的使用說明,文章圍繞主題展開詳細的內(nèi)容介紹,具有一定的參考價值,需要的朋友可以參考一下2022-09-09
uniapp實現(xiàn)圖片壓縮并上傳的實戰(zhàn)步驟
本文介紹了如何在uniapp中封裝一個既能支持H5和小程序雙平臺,又能實現(xiàn)圖片自動壓縮并處理接口響應(yīng)異常的自定義上傳方法useUploadMethod,文章詳細分析了痛點,提出了整體架構(gòu)設(shè)計,需要的朋友可以參考下2026-02-02
用javascript模仿ie的自動完成類似自動完成功的表單
最近在寫一個javascript框架,看見網(wǎng)上有不少自動完成功能的表單,于是用javascript寫了一個,需要的朋友可以參考下2012-12-12
靜態(tài)頁面也可以實現(xiàn)預(yù)覽 列表不同的顯示方式
靜態(tài)頁面也可以實現(xiàn)預(yù)覽 列表不同的顯示方式...2006-10-10
基于Bootstrap實現(xiàn)的下拉菜單手機端不能選擇菜單項的原因附解決辦法
小編使用bootstrap做的下拉菜單在電腦瀏覽器中可以正常使用,在手機瀏覽器中能彈出下拉列表卻不能選擇列表中的菜單項,怎么回事,如何解決呢?下面小編給大家分享下具體原因及解決辦法,一起看下吧2016-07-07
一文詳解JavaScript如何安全的進行數(shù)據(jù)獲取
這篇文章主要為大家介紹了JavaScript如何安全的進行數(shù)據(jù)獲取方法詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-03-03
JavaScript將字符串轉(zhuǎn)換成字符編碼列表的方法
這篇文章主要介紹了JavaScript將字符串轉(zhuǎn)換成字符編碼列表的方法,實例分析了javascript中charCodeAt函數(shù)的使用技巧,具有一定參考借鑒價值,需要的朋友可以參考下2015-03-03

