背景
不知道大家项目中是否经常遇到多条件分支判断逻辑,如果你还是用if-else
或者 switch
写了一长串的话,不妨试试用对象字面量的方式,能很大程度简化代码。
demo
原始
function switchWay(type) {
switch(type) {
case 't1':
return [1];
case 't2':
return [2];
case 't3':
return [3];
default:
return [0]
}
}
对象字面量改写
const obj = {
t1:[1],
t2:[2],
t3:[3]
}
function objWay(type){
return obj[type] || [0]
}