1.单个if语句优化
①&& || 优化
if (e) {
this.getList()
}
优化后
e && this.getList()
2.if/else语句优化
①三元运算符优化
if (a) {
逻辑1;
} else {
逻辑2;
}
优化后
a ? 逻辑1 : 逻辑2;
3.单if多条件优化
①includes优化
function change(type) {
if (type === 'jpg' || type === 'png' || type === 'svg') {
逻辑;
}
}
优化后
function change(type) {
const imgType = ['jpg', 'png', 'svg']
if (imgType.includes(type)) {
逻辑;
}
}
4.处理多层复杂条件
①低阶switch case优化(switch case比较用的是全等,注意类型)
if (e === 1) {
逻辑1;
} else if (e === 2) {
逻辑2;
} else {
逻辑3;
}
优化后
switch (e) {
case 1: 逻辑1;
breack;
case 2: 逻辑2;
breack;
default: 逻辑3;
breack;
}
②中阶key-value对象枚举优化
function change(val) {
let array = {
'A' : 逻辑1,
'B' : 逻辑2,
'C' : 逻辑3,
'D' : 逻辑4
}
let newArray = array(val)
newArray()
}
③高阶通过map实现优化
if (mode == 'key') {
if (this.type === 'A') {
逻辑1;
} else if (this.type === 'B') {
逻辑2;
} else if (this.type === 'C') {
逻辑3
}
} else if (mode == 'vas') {
if (this.type === 'D') {
逻辑4;
} else if (this.type === 'E') {
逻辑5;
} else if (this.type === 'F') {
逻辑6;
}
}
优化后
let array = new Map([
['key_A', 逻辑1],
['key_B', 逻辑2],
['key_C', 逻辑3],
['vas_D', 逻辑4],
['vas_E', 逻辑5]
['vas_F', 逻辑6],
])
function change(mode, type) {
let value = `${mode}_${type}`
let newArray = array.get(value)
方法(newArray)
}