前端如何写出优雅的 if……else 判断

撸代码这么多年,在我见过的大部分写程序的人当中,写逻辑判断的时候都是if……else,或者switch……case,我今天要说的并不是他们不好,而是还有更好的,更优雅的表达方式。


前端如何写出优雅的 if……else 判断


在任何语言中,都少不了逻辑判断。在js中,像这样的代码我想大家已经司空见惯了;

这里我们默认index为一个可变变量;

<code>if(index==='a'){  
//满足条件1
}elseif(index==='b'){
//满足条件2
}elseif(index==='c'){
//满足条件3
}/<code>

而如果是满足"条件1"的情况有很多种呢?那么代码就变成了这样:

<code>if(
index === 'a' ||
index === 'a1'||
index === 'a2' ||
index === 'a3'||
index === 'a4'||
index === 'a5'||
……){
//满足条件1
}else if(index === 'b'){
//满足条件2
}else if(index === 'c'){
//满足条件3
}/<code>

这时我们就可以这样写:

<code>letarr=['a','a1','a2','a3','a4','a5'];
if(arr.includes(index))//返回布尔值,true即为存在

//执行代码
}
//或者
if(arr.indexOf(index)>-1){//indexOf返回找到的下标,没有找到返回-1
//执行代码
}/<code>

如果我们使用switch……case:

<code>switch(index){  
case 'a':
//……
break;
case 'b':
//……
break;
case 'c':
//……
break;
}/<code>

不知道大家发现没有,使用switch的时候其实很难像if判断那样做到同时满足多个条件执行相同代码的情况,相对来说,if更为灵活;好,那我们继续;


而对于那种满足条件执行相同函数,但函数执行参数不同的代码,比如:

<code>function add(x){console.log(x+1);}if(index=='a'){  add('参数a')}elseif(index=='b'){  add('参数b')}elseif(index=='c'){  add('参数c')}//我们可以优化成-------------华丽的分割线-----------------let Obj={  'a':'参数a','b':'参数b','c':'参数c'}add(Obj[index]);/<code>


如果是二元条件判断或者是三元条件判断(很少情况,大于三层的if判断可以考虑是不是逻辑有问题了),比如:

<code>lettype='缴费类',index='a'; 
function payCost(pay){
alert('缴费类:'+pay)
}
function topUp(pay){
alert('充值类:'+pay)
}
//一般写法
if(type=='缴费类'){
if(index=='a'){
payCost('a')
}else if(index=='b'){
payCost('b')
}
}else if(tyle=='充值类'){
if(index=='a'){
topUp('a')
}else if(index=='b'){
topUp('b')
}
}
//根据自己的需求改造代码
let Obj={ '缴费类a':payCost, '缴费类b':payCost, '充值类a':topUp, '充值类b':topUp }
Obj[type+index](index);/<code>

当然,我们写程序时出现的情况可能有很多种,也可能比这个复杂,我们具体情况具体分析。这里只是一个参考的Demo;

最后,如果你非要写个三层、四层嵌套的逻辑判断,那么接下来的这个方案,就是为了解决你这个问题的,这里我们会使用到js中的Map数据结构,具体怎么做,上代码:

<code>let type = 'SUV'; //类型
let color = 'red'; //颜色
let seatCount = 5; //座位数

//查询满足条件的车型数量
function getCount(key,count) { console.log("车型:"+key.type); console.log("颜色:"+key.color); console.log("座位数:"+key.seatCount); console.log("剩余数量:"+count)}

const mapList = new Map([
[{type: 'SUV', color: 'pink',seatCount:5}, '25'],
[{type: '小轿车', color: 'white',seatCount:5}, '123'],
[{type: 'SUV', color: 'red',seatCount:7}, '42'],
[{type: '火车', color: 'pink',seatCount:1005}, '121'],
[{type: '小轿车', color: 'white',seatCount:5}, '32'],
[{type: 'SUV', color: 'black',seatCount:6}, '13'],
[{type: '跑车', color: 'red',seatCount:2}, '12'],
[{type: '跑车', color: 'palegreen',seatCount:2}, '32'],
[{type: '小轿车', color: 'pink',seatCount:7}, '43'],
[{type: 'SUV', color: 'red',seatCount:5}, '112']
]);
//过滤出满足条件的数据;
const items = [...mapList].filter(function([key, value]){
return key.type === type && key.color === color && key.seatCount === seatCount
});
const [key, value] = items[0]; getCount(key,value);/<code>

如果还有更复杂的,比如满足好几个状态执行同一个函数,那你可以尝试使用正则匹配,这里就不在一一举例,反正遇到问题多思考,多动手,一定会有更好的解决办法。

如果想学习更多前端知识,关注我,更多精彩内容等着你……


前端如何写出优雅的 if……else 判断


分享到:


相關文章: