js优化条件查询语句
优化前的条件判断:
/**
* 优化前
* */
function printAnimalDetails(animal) {
let result = null
if (animal) {
if (animal.type) {
if (animal.name) {
if (animal.gender) {
result = `${animal.name} is a ${animal.gender}---${animal.type}`
} else {
result = 'no animal gender'
}
} else {
result = 'no animal type'
}
} else {
result = 'no animal type'
}
} else {
result = 'no animal'
}
return result
}
优化后的条件判断:
/**
* 优化后
* 利用 提前退出 和 提前返回 的思想
*/
const optimizationPrintAnimalDetails = (animal) => {
if (!animal) return 'no animal'
if (!animal.type) return 'no animal type'
if (!animal.name) return 'no animal name'
if (!animal.gender) return 'no animal gender'
return `${animal.name} is a ${animal.gender}---${animal.type}`
}
测试优化后的代码
console.log(optimizationPrintAnimalDetails({name:'大黄'})) // no animal type
console.log(optimizationPrintAnimalDetails({name:'大黄',type:'金毛',gender:'公'}))// 大黄 is a 公---金毛
console.log(optimizationPrintAnimalDetails()) // no animal