0 说明
代码中if太多了怎么办
通过对象来实现优化是常用的方法,这里做个整理
1 场景
1.1 一层逻辑处理
// 优化前
if(inValue === "a"){
function1()
}
if(inValue === "b"){
function2()
}
// 优化后
const funcs = {
"a": function1,
"b": function2
}
funcs[inValue]()
1.2 更高优先级处理
// 优化前
if(inValue === '330000'){
if(inValue === '330100'){
return console.log('杭州')
}
if(inValue === '330200'){
return console.log('宁波')
}
return console.log('浙江')
}
// 优化后
const funcs = {
"11": null,
"33": queryZhejiang,
"330100": queryHangzhou,
"330200": queryNingbo,
}
const provinceCode = resultCode.slice(0,2)
const cityCode = resultCode.slice(2)
const method = funcs[provinceCode] || funcs[cityCode]
method()
1.3 细分条件处理
// 优化前
if(errCode === "307001" || errCode === "307003" || errCode === "307009"){
return failFunc(errCode)
}
else{
if(pageType === "a"){
if(detailType === "1"){
return successAFunc1(num)
}
if(detailType === "2"){
return successAFunc2(num)
}
}
if(pageType === "b"){
return successBFunc(num)
}
}
// 优化后
const funcs = {
"307001": failFunc,
"307003": failFunc,
"307009": failFunc,
"a-1": successAFunc1,
"a-2": successAFunc2,
"b": successBFunc
}
if(errCode in funcs){
return funcs[errCode](errCode)
}
const key = `${
pageType}-${
detailType}`;
if(key in funcs){
return funcs[key](num)
}
2 总结
通过对象来实现场景判断,可以大大提高代码的可读性、可维护性,减少大量的if判断,并能实现场景判断与功能代码两者的分离
另外,很感谢chatgpt的指导哈哈哈,基本把需要整理的代码结构写个demo发给chatgpt,就能给你不同的优化方案(当然有时可能会有错误需要自己甄别