1.减少没必要的if...else判断
if(value === 1) {
flag = true;
} else {
flag = false;
}
flag = value === 1
2.使用switch,object或者Map代替
function fun1(status){
if (status == 1) {
alert('成功:',status)
go('IndexPage')
} else if (status == 2) {
alert('失败:',status)
go('failPage')
} else if (status == 3) {
alert('失败:',status)
go('failPage')
} else if (status == 4) {
alert('超时:',status)
go('timeoutPage')
} else if (status == 5) {
alert('系统内部错误:',status)
go('errorPage')
} else {
alert('其他提示:',status)
go('otherPage')
}
}
function fun1(status){
switch (status) {
case 1:
alert('成功:',status)
go('IndexPage')
break
case 2:
case 3:
alert('失败:',status)
go('failPage')
break
case 4:
alert('超时:',status)
go('timeoutPage')
break
case 5:
alert('系统内部错误:',status)
go('errorPage')
break
default:
alert('其他提示:',status)
go('otherPage')
break
}
}
const actions = {
'1': ['成功', 'IndexPage'],
'2': ['失败', 'failPage'],
'3': ['失败', 'failPage'],
'4': ['超时', 'timeoutPage'],
'5': ['系统内部错误', 'errorPage'],
'default': ['其他', 'otherIndex']
}
function fun(status){
let action = actions[status] || actions['default']
logName = action[0]
pageName = action[1]
alert(logName)
go(pageName)
}
const actions2 = new Map([
[1, ['成功', 'IndexPage']],
[2, ['失败', 'failPage']],
[3, ['失败', 'failPage']],
[4, ['超时', 'timeoutPage']],
[5, ['系统内部错区', 'errorPage']],
['default', ['其他', 'otherPage']]
])
function fun(status){
let action = actions2.get(status) || actions2.get('default')
alert(action[0])
go(action[1])
}
3.代码健壮性处理用?.代替&&
res&&res.data&&res.data.forEach(()=>{...})
res?.data?.forEach(()=>{...})
一个为 null 和 undefined 的判断,减少 || 类型的处理,用 ??
const arr=res&&res.data||[]
const arr=res?.data??[]
4.校验多个表单项不能为空,使用策略模式代替 if-else
const formState = reactive({
name: '',
age: 16,
sex: undefined
});
if(!formState.name) {
message.error('姓名不能为空!');
}else if(!formState.age){
message.error('年龄不能为空!');
}else if(!formState.sex){
message.error('性别不能为空!');
}
const errorMessageObj = {
name: '姓名不能为空!',
age: '年龄不能为空!',
sex: '性别不能为空!'
};
Object.keys(formState).forEach(key => {
if(!formState[key]) {
message.error(errorMessageObj[key])
}
});
5.利用filter,some,every优化代码
const openarr=[]
arr.forEach(item=>{
if(item.isopen){
openarr.push(item)
}
})
const openarr=arr.filter(item=>item.isopen)
let isFill=true
arr.forEach(item=>{
if(!item.name){
isFill=false
}
})
const isFill=arr.every(item => !item.name)
const isNull=arr.some(item => !item.name)
6.使用数组或者字符串的 includes 方法,代替 indexOf 方法
const arr = ['a', 'b', 'c']
if (arr.indexOf('a') !== -1)
if (arr.includes('a'))
7.使用 Promise.allSettled 并行请求
const getCodeFunc = async () => {
const promises = [
getCodeApi({type: "sex"}),
getCodeApi({type: "class"}),
getCodeApi({type: "type"}),
];
const results = await Promise.allSettled(promises);
sexList = results[0]?.value?.data;
classList = results[1]?.value?.data;
typeList = results[2]?.value?.data;
};