开始
用 return
替代 if-else
场景:互斥的条件判断
function test(data){
let result = '';
if(data<10){
result = 'if'
}else{
result = 'else'
}
return result
}
==优化成==>
function test(data){
let result = '';
if(data<10){
return result = 'if'
}
return result = 'else'
}
使用 Array
的 includes
方法
场景:多种条件对应相同的处理
function region(province){
let result = ""
if(province === "广东"|| province === "广西"|| province === "福建" || province === "浙江" || province === "云南")
{
result = "南方"
}
if(province === "河北"|| province === "黑龙江"|| province === "辽宁" || province === "山东" || province === "吉林")
{
result = "北方"
}
}
==优化成==>
function region(province){
let result = ""
let northProvinceArr = ["河北","黑龙江","辽宁","山东","吉林"]
let southProvinceArr = ["广东","广西","福建","浙江","云南"]
if(southProvinceArr.includes(province)) result = "南方";
if(northProvinceArr.includes(province)) result = "北方"
}
策略模式
场景:并列的多条件判断
function permission(role){
if(role === “operations”){
getOperationPermission()
}else if(role === "admin"){
getAdminPermission()
}else if(role === "superAdmin"){
getSuperAdminPermission()
}else if(role === "user"){
getUserPermission()
}
}
// 或者下面这样
function permission(role){
switch(role){
case "operations": {
getOperationPermission();
break;
}
case "admin": {
getAdminPermission();
break;
}
case "superAdmin": {
getSuperAdminPermission();
break;
}
case "user": {
getUserPermission();
break;
}
}
}
==优化成==>
function permission(role){
const actions = {
operations: getOperationPermission,
admin: getAdminPermission,
superAdmin: getSuperAdminPermission,
user: getUserPermission,
}
actions[role].call()
}
对象数组
场景:多条件嵌套多分支判断
function getAmount(type,quantity,price){
let result = 0;
if(type === "shoe"){
if(quantity>5){
result = price * quantity * 0.7
}else{
result = price * quantity * 0.8
}
}else{
if(quantity>5){
result = price * quantity * 0.9
}else{
result = price * quantity * 0.95
}
}
}
==优化成==>
function getAmount(type,quantity,price){
let result = 0;
const isShoe = type === "shoe";
const greater = quantity>5;
const discountArr = [
{isShoe: true, greater: true, amount: 0.7 * quantity * price }
{isShoe: true, greater: false, amount: 0.8 * quantity * price }
{isShoe: false, greater: true, amount: 0.9 * quantity * price }
{isShoe: false, greater: false, amount: 0.95 * quantity * price }
]
result = discountArr.filter(item=>
item.isShoe === isShoe && item.greater === greater)[0].amount
}
三元表达式
在某些情境下,使用三元表达式实现条件判断会是个不错的选择,它可以让代码更加简洁。
if(a>0){
a+=1;
}else{
a-=1
}
==优化成==>
a>0? a+=1 : a-=1;