代码优雅的处理

75 阅读1分钟

if else优化

1.单个if else优化

//优化前
let flag=true
if(flag){
//执行业务逻辑
}else{
return
}

//初步优化 
let flag=true
if(!flag)return
//执行业务逻辑

//另一种优化
flag&&doSomething()  //flag为true才执行后续业务逻辑

2.单个if else带返回值优化

function getFlag(flag){
 if(flag){
     return '真'
  }else{
     return '假'
}

//优化后
funtion getFlag(flag){
return flag?'真':'假'
}

3.单个if else 执行不同方法优化

function do(flag){
 flag?doSuccess():doFalse()
}

4.多个if else带返回值优化

function getCountry(status){
const map={
     1:"中国",
     2:"英国",
     3:"法国",
     4:"德国",
  }
  return map[status]??'未查到'
  //?? (空值合并运算符) 当左边为null和undefined
}

//策略模式优化
function getCountry(status){
 const map=new Map([
 [1,'中国'],
 [1,'英国'],
 [1,'法国'],
 [1,'德国'],   
 ])
 return map[status]??'未查到'
}

console.log优化


console.log('age',age)
console.log({age})

Vue中优化

1.v-if多条件判断

普通写法 v-if="condition === 0 || condition === 1 || condition === 2"
简洁写法 v-if="[0, 1, 2].includes(condition)"   <!--括号里可以是字符串和数字-->

2.不要在template中写计算复杂的逻辑

//反例:
<div>
    {{
  fullName.split(' ').map(function (word) {
    return word[0].toUpperCase() + word.slice(1)
  }).join(' ')
}}
</div>

//推荐:
<!-- 在模板中 -->
<div>{{ normalizedFullName }}</div>
// 复杂表达式已经移入一个计算属性
computed: {
  normalizedFullName: function () {
    return this.fullName.split(' ').map(function (word) {
      return word[0].toUpperCase() + word.slice(1)
    }).join(' ')
  }
}