24 js优化条件语句
function printAnimalDetaills(animal) {
let res = null
if (animal){
if (animal.type){
if (animal.name){
if (animal.gender){
res = `${animal.name} is a ${animal.gender} - ${animal.type}`
}else {
res = 'no animal gender'
}
}else {
res = 'no animal name'
}
}else {
res = 'no animal type'
}
}else {
res = 'no animal'
}
return res
}
//逻辑运算符方式可读性差
function printA(animal) {
return (animal &&
(animal.type &&
(animal.name &&
(animal.gender && (
`${animal.name} is a ${animal.gender} - ${animal.type}`
)
|| 'no animal gender')
|| 'no animal name')
|| 'no animal type')
|| 'no animal')
}
//提前退出 和 提前返回
//采用ES6解构赋值
function printB(animal) {
if (!animal)return 'no animal'
let {type,name,gender} = animal
if (!type)return 'no animal type'
if (!name)return 'no animal name'
if (!gender)return 'no animal gender'
return `${name} is a ${gender} - ${type}`
}
console.log(printAnimalDetaills())
console.log(printAnimalDetaills({}))
console.log(printAnimalDetaills({type:'1'}))
console.log(printAnimalDetaills({type:'1',name:'2'}))
console.log(printAnimalDetaills({type:'1',name:'2',gender:'3'}))
console.log(printA())
console.log(printA({}))
console.log(printA({type:'1'}))
console.log(printA({type:'1',name:'2'}))
console.log(printA({type:'1',name:'2',gender:'3'}))
console.log(printB())
console.log(printB({}))
console.log(printB({type:'1'}))
console.log(printB({type:'1',name:'2'}))
console.log(printB({type:'1',name:'2',gender:'3'}))