1.对多个条件使用Array.includes
eg: function test(fruit){ function test(fruit){
if(fruit=='apple' || fruit=='cherry' ){ 可改写为
console.log('red') =================================>> const redFruits=['apple','cherry','strawberry'];
} if(redFruits.includes(fruit)){
console.log('red')
}
} }
2.更少的嵌套,尽早的返回
eg: 如果没有水果名称,抛出错误
如果红色水果数量超过10个,接受并打印
function test(fruit, quantity){
const redFruits=['apple','cherry','strawberry'];
if(!fruit) throw new Error('No fruit!');
if(!redFruits.includes(fruit)) return;
console.log('red'');
if(quantity >10){
console.log('big quantity')
}
}
3.使用默认的函数参数和结构
4.选择Map或对象字面量,而不是switch语句
function test(color){
switch(color){
case 'red':
return ['apple','strawberry'];
case 'yellow':
return['banana','pineapple'];
case 'purple':
return ['grape','plum'];
default:
reutrn [];
}
}
test(null)
test('yellow')
||||||||||
|||||||||| 代码改造后
||||||||||
||||||||||
||||||||||
改法一:const fruitColor={
red:['apple','strawberry'],
yellow:['banana','pineapple'],
purple:['grape','plum']
}
function test(color){
return fruitColor[color] || [];
}
改法二:
const fruitColor=new Map()
.set('red',['apple','strawberry'])
.set('yellow',['banana','pineapple'])
.set('purple',['grape','plum'])
function test(color){
return fruitColor.get(color) ||[]
}
改法三:
const fruits=[
{name:'apple',color:'red'},
{name:'strawberry',color:'red'},
{name:'banana',color:'yellow'},
{name:'pineapple',color:'yellow},
]
function test(color){
return fruits.filter(f>=f.color==color)
}
5.所有或部分使用Array.every&Array.some的条件
eg:检查所有的水果是否都是红色的
const fruits=[
{name:'strawberry',color:'red'},
{name:'banana',color:'yellow'},
]
function test(){
const isAllRed=fruits.every(f>=f.color=='red');
console.log(isAllRed)
}
eg:判断任何一种水果是否为红色
const fruits=[
{name:'strawberry',color:'red'},
{name:'banana',color:'yellow'},
]
function test(){
const isAllRed=fruits.some(f>=f.color=='red');
console.log(isAllRed)
}