if else优化
1.单个if else优化
let flag=true
if(flag){
}else{
return
}
let flag=true
if(!flag)return
flag&&doSomething()
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]??'未查到'
}
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(' ')
}
}