优化if语句中相同的代码案例
优化前
if ([0, 1].includes(loadType)) {
this.energyData = res.data.energyItems;
this.energyArr = this.energyData.length > 9 ? this.energyData.slice(0, 9) : (this.energyArr = this.energyData)
this.getEnergyRank()
}
if ([0, 2].includes(loadType)) {
this.constData = res.data.energyItems;
this.costArr = this.constData.length > 9 ? this.constData.slice(0, 9) : (this.costArr = this.constData)
this.costRank()
}
1
2
3
4
5
6
7
8
9
10
2
3
4
5
6
7
8
9
10
优化后
function handle({thisKey,dataKey,thisArr}) {
this[thisKey] = res.data[dataKey];
this[thisArr] = this[thisKey].length > 9 ? this[thisKey].slice(0, 9) : (this[thisArr] = this[thisKey])
}
let key = {
1: {
dataKey: 'energyItems',
thisKey: 'energyData',
thisArr: 'energyArr'
},
2: {
dataKey: 'costItems',
thisKey: 'constData',
thisArr: 'costArr'
}
}
if ([0, 1].includes(loadType)) {
this.handle(key[1])
this.getEnergyRank()
}
if ([0, 2].includes(loadType)) {
this.handle(key[2])
this.costRank()
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
在线编辑 (opens new window)
上次更新: 2021/11/14, 07:48:46