项目中常见的代码优化方案

141 阅读2分钟

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')//跳页面方法
      }
}
 
//switch写法
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
  }
}
 
//object写法
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)//跳页面方法
}
 
//Map写法
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(()=>{...})
一个为 nullundefined 的判断,减少 || 类型的处理,用 ??

//示范案例:
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;
};