includes方法 数组.includes(元素)
function printAnimals(animal){
const animals=['dog','cat','fish']
if(animals.includes(animal))
console.log('this is a ${animal}')
}
printAnimals('dog')//this is a dog
提前退出/提前返回(非常实用)
需求:
如果没有动物,抛出异常
否则 打印动物的类型、名字、性别
function printAnimalsDetails(animal){
var 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 name'
}
}else{
result='no animal type'
}
}else{
result='no animal'
}
return result
}
用 提前退出 和 提前返回 改写
const printAnimalsDetails=({type,name,gender}={})=>{
if(!type) return 'no animal type'//这就是提前退出,提前返回
if(!name) return 'no animal name'
if(!gender) return 'no animal gender'
return '${animal.name} is a ${animal.gender} ${animal.type}'
}