//适用场景 if(config1=='xxx'||config2=='xxx'||config3=='xxx')
//更改为 if(or())
export function or(){
do{
if(config1=='xxx'){
console.log('满足条件一')
break
}
if(config2=='xxx'){
break
}
if(config3=='xxx'){
break
}
//所有条件都不满足返回false
console.log('所有条件都不满足')
return false
}
while(false)
//只要满足一个返回true
return true
}
//适用场景 if(config1=='xxx'&&config2=='xxx'&&config3=='xxx')
//多if层级嵌套
// if(config1=='xxx'){
// if(config2=='xxx'){
// if(config3=='xxx'){
// }
// }
// }
//更改为 if(and())
export function and(){
do{
if(config1=='xxx'){
}
else{
console.log('不满足条件一')
break
}
if(config2=='xxx'){
}
else{
console.log('不满足条件二')
break
}
if(config3=='xxx'){
}
else{
console.log('不满足条件三')
break
}
//所有条件都满足返回true
console.log()
return false
}
while(false)
//只要有一个不满足返回false
return true
}
//组合拳 适用场景if((config1==1&&config2==2)||config3==3)只看最外层为or
// 更改为if(or())
const map={config1:1,config2:2,config:3}
export function or(map){
do{
if(and(map)){
console.log('满足条件一')
break
}
if(map.config3==3){
break
}
//所有条件都不满足返回false
console.log('所有条件都不满足')
return false
}
while(false)
//只要满足一个返回true
return true
}
export function and(map){
do{
if(map.config1=='xxx'){
}
else{
console.log('不满足条件一')
break
}
if(map.config2=='xxx'){
}
else{
console.log('不满足条件二')
break
}
//所有条件都满足返回true
return false
}
while(false)
//只要有一个不满足返回false
return true
}
嵌套条件if分区模板 (前端)
最新推荐文章于 2025-10-21 09:27:36 发布
本文介绍了一种重构技术,将复杂的if条件语句替换为自定义的`or`和`and`函数,提高代码可读性和效率。通过示例展示了如何将多层if嵌套转换为简洁的函数调用,适用于处理配置项检查的场景。
1458

被折叠的 条评论
为什么被折叠?



