开发中有时会遇到多个条件,执行相同的语句,也就是多个||这种:

1
2
3
if (status === 'process' || status === 'wait' || status === 'fail') {
  doSomething()
}

这种写法语义性、可读性都不太好。可以通过switch case或includes这种进行改造。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
switch case
switch(status) {
  case 'process':
  case 'wait':
  case 'fail':
    doSomething()
}
includes
const enum = ['process', 'wait', 'fail']
if (enum.includes(status)) {
  doSomething()