1、减少if…else面条代码
const getPrice = (name) => {
if (name === 'hamburger') {
return 20
} else if (name === 'French fries') {
return 15
} else if (name === 'ice cream') {
return 5
}
}
console.log(getPrice('hamburger')) // 20
优化:
const foodMap = {
'hamburger' : 20,
'French fries' : 15,
'ice cream' : 5,
'Coffee' : 12
}
const getPrice = (name) => {
return foodMap[name]
}
console.log(getPrice('hamburger')) // 20
2、管道操作取代冗余循环
const foods = [{
name: 'hamburger',
group: 1
}, {
name: 'French fries',
group: 1
}, {
name: 'Coffee',
group: 2
}, {
name: 'ice cream',
group: 1
}]
找出属于套餐1的食物,先对数组过滤再重组
const names = foods
.filter( i => i.group === 1 )
.map( i => i.name )
console.log(names) // ['hamburger', 'French fries', 'ice cream']
3、find取代冗余循环
食品对象数组中按照属性值查找特定的食物
const hamburger = foods
.find( i => i.name === 'hamburger' && i.group === 1)
console.log(hamburger) // {name: 'hamburger', group: 1}
4、includes取代冗余循环
一碗「康某傅老坛酸菜牛肉面」有「酸菜」,「面」,「牛肉粒」,「烟头」和「脚皮」组成,那我们想用函数证实这个面里面是否有脚皮
const sauerkrautBeefNoodles = ['a' , 'b' , 'c' , 'd']
const hasD = sauerkrautBeefNoodles.includes('d')
console.log(hasD) // true
5、result返回值
const getUrl = (content, prefix, suffix) => {
let result = content
if (prefix) {
result = `${
prefix}${
result}`
}
if (suffix) {
result = `${
result}${
suffix}`
}
return result
}
console.log(getUrl('www.apifox', 'https://', '.cn')) // https://www.apifox.cn
6、提前返回
const activeParentKeys = (selectKeys) => {
if (!selectKeys) return []
if (selectKeys !== 'key1') {
return getParentKeys(selectKeys)
}
return []
}
7、保持对象完整
解构完整对象
const getDocDetail = (data) => {
const {
icon, content}
console.log(icon)
console.log(content)
}
getDocDetail(data)
8、巧用运算符
let activeKey = selectedKey || ''