优化写法一(常用高级写法):用Map对象,以Object对象作为key:判断条件一个至多个都可以
![](https://i-blog.csdnimg.cn/blog_migrate/37b2aa5d09945efc13bb43a54afa5f18.png)
let divide = 'dev'
let status = 2
const actions = new Map([
[{identity:'dev',status:1},()=>{/*do sth*/}],
[{identity:'dev',status:2},()=>{/*do sth*/}],
[{identity:'dev',status:3},()=>{/*do sth*/}],
//...
])
// 同时满足key.identity == divide && key.status == status
let action = [...actions].filter(([key,value])=>(key.identity == divide && key.status == status))
action.forEach(([key,value])=>value.call(window)) //this
如果status不同,后面处理的function不一样,处理方法一样,写不同的function就可以,如下:
![](https://i-blog.csdnimg.cn/blog_migrate/f93f155faf984f7a40e4f71ac9521fc6.png)
const publicKeyboardShortcuts = (evt: KeyboardEvent) => {
let divide = 'dev';//变量
let status = 2;//变量
const actions = new Map([
[{identity: 'dev', status: 1}, functionA],
[{identity: 'dev', status: 2}, functionB],
[{identity: 'dev', status: 3}, functionC],
[{identity: 'dev', status: 4}, functionD],
//...
])
let action = [...actions].filter(([key, value]) => (key.identity == divide && key.status == status))
action.forEach(([key, value]) => value.call(window)) //this
}
const functionA = () => {
}
const functionB = () => {
}
const functionC = () => {
}
const functionD = () => {
}
上面逻辑使用Object对象来实现如下:
![](https://i-blog.csdnimg.cn/blog_migrate/b1cc668848eac2d6f0ff3e90c6c75c1d.png)
const publicKeyboardShortcuts = (evt: KeyboardEvent) => {
let divide = 'dev'
let status = 2
const actions = [
['dev_1', ()=>{/*do sth*/}],
['dev_2', ()=>{/*do sth*/}],
['dev_3', ()=>{/*do sth*/}],
...
]
let action = actions.get(`${divide}_${status}`) || actions.get('default');
action.call(window) //this
}
如果判断条件是 1-3 都执行functionA方法,判断条件是 4-5 都去执行functionB方法,这种情况下就可以使用正则去匹配
我们正常的处理逻辑是:每一个都写一遍方法如下
![](https://i-blog.csdnimg.cn/blog_migrate/f88d64e972a764241e96d167506790d6.png)
const publicKeyboardShortcuts = (evt: KeyboardEvent) => {
let divide = 'dev';//变量
let status = 2;//变量
const actions = new Map([
[{identity: 'dev', status: 1}, functionA],
[{identity: 'dev', status: 2}, functionA],
[{identity: 'dev', status: 3}, functionA],
[{identity: 'dev', status: 4}, functionB],
[{identity: 'dev', status: 5}, functionB],
[{identity: 'dev', status: 6}, functionC],
//...
])
let action = [...actions].filter(([key, value]) => (key.identity == divide && key.status == status))
action.forEach(([key, value]) => value.call(window)) //this
}
const functionA = () => {
}
const functionB = () => {
}
const functionC = () => {
}
优化之后,使用正则处理的方法:用正则类型作为key,利用数组循环的特性,符合正则条件的逻辑都会被执行
![](https://i-blog.csdnimg.cn/blog_migrate/95754d1263e5e250b70b45ff14e42a98.png)
详细看优化:
https://blog.csdn.net/weixin_42333548/article/details/107835102