js策略模式减少 if else 判断(骚操作)快来看看吧!

71 阅读1分钟

策略模式的使用,避免过多的if else判断,也可以替代简单逻辑的switch

// 未使用策略模式
const formatDemandItemType = (value) => {
    switch (value) {
        case 1:
            return  '初级'
        case 2:
            return  '中级'
        case 3:
            return  '高级'
    }
}


// 策略模式
const formatDemandItemType2 = (value) => { // 用形参匹配
    const obj = {
        1:  '初级' ,
        2:  '中级' ,
        3:  '高级' ,
    }
    
    return obj[value]
}
console.log(formatDemandItemType2(1)) // 输出初级