1.Array.include()
需要用到大量或语句判断的
function printAnimals(animal){
if(anmial === 'dog' || anmial === 'cat'){
console.log(animal)
}
}
// 优化
function printAnimals(animal){
let anmials = ['dog','cat']
if(anmials.includes(animal)){
console.log(animal)
}
}
2.提前退出和提前返回
遇到多个if else 或者if else多层嵌套的时候,可以用到下面方法,提前退出和返回
const printAnimals = ({type,name,gender}={}) => {
if(!type) return 'no type'
if(!name) return 'no name'
if(!gender) return 'no gender'
return type + name + gender
}
3.用对象字面量替换switch语句
function printFruits(color){
switch(color){
case 'red'
return 'apple'
case 'yellow'
return 'banana'
default:
return []
}
}
// 优化(对象字面量)
const fruitsColor = {
red: 'apple',
yellow: 'banana'
}
function printFruits(color){
return fruitsColor[color] || []
}
4.Array.some 和 Array.every
Array.every 只要所有都满足才会返回true
Array.some只要一个都满足就会返回true
const fruits = [
{name: 'apple',color: 'red'},
{name: 'banana',color: 'yellow'},
]
//检查所有水果是否为红色
console.log(fruits.every(item => item.color === 'red')) //false
// 检查是否有红色水果
console.log(fruits.some(item => item.color === 'red')) // true