优雅条件判断
用 return 替代 if - else
场景:互斥的条件判断
function test(data){ let result = ''; if(data<10){ result = 'if' }else{ result = 'else' } return result } ==优化成==> function test(data){ let result = ''; if(data<10){ return result = 'if' } return result = 'else' }
使用 Array 的 includes 方法
场景:多种条件对应相同的处理
function region(province){ let result = "" if(province === "广东"|| province === "广西"|| province === "福建" || province === "浙江" || province === "云南") { result = "南方" } if(province === "河北"|| province === "黑龙江"|| province === "辽宁" || province === "山东" || province === "吉林") { result = "北方" } } ==优化成==> function region(province){ let result = "" let northProvinceArr = ["河北","黑龙江","辽宁","山东","吉林"] let southProvinceArr = ["广东","广西","福建","浙江","云南"] if(southProvinceArr.includes(province)) result = "南方"; if(northProvinceArr.includes(province)) result = "北方" }
策略模式
场景:并列的多条件判断
function permission(role){ if(role === “operations”){ getOperationPermission() }else if(role === "admin"){ getAdminPermission() }else if(role === "superAdmin"){ getSuperAdminPermission() }else if(role === "user"){ getUserPermission() } } // 或者下面这样 function permission(role){ switch(role){ case "operations": { getOperationPermission(); break; } case "admin": { getAdminPermission(); break; } case "superAdmin": { getSuperAdminPermission(); break; } case "user": { getUserPermission(); break; } } } ==优化成==> function permission(role){ const actions = { operations: getOperationPermission, admin: getAdminPermission, superAdmin: getSuperAdminPermission, user: getUserPermission, } actions[role].call() }