if else 写多了,没别的就是恶心

1. 三元运算 ,或形式

if(flag){  a=b}else{  a=c}

==> a=a || b
或者 a= flag? b: c

2.数组匹配形式

后盾接口通常会返回这种数据:
fruit: 0 // 0=苹果,1=梨子,2=桔子,3=柠檬,4=芒果...

var _f = ['苹果','梨子','桔子','柠檬','芒果'];shuiguo = _f[fruit];

3. switch case形式

  if (res.state === 'SUCCESS') {        //TODO    } else if (res.state === 'FAIL') {        //TODO    } else {        //TODO    }

优化应用switch case

 switch (res.state) {        case 'SUCCESS':            //TODO            break;        case 'FAIL':            //TODO            break;        default :            //TODO    }

4. 哈希表的形式

if (key == "Apple") {    val = "Jobs";} else if (key == "microsoft"){    val = "Gates";} else if (key == "Google"){    val = "Larry";} 

能够用hash

var ceos = {"Apple":"Jobs", "microsoft":"Gates", "Google":"Larry"};val = ceos[key];

5. new Map 形式也能够
下面的案例 能够改成

let map = new Map([  ['Apple' , 'Jons'] ,  ['microsoft' , 'Gates'] ,  ['Google' , 'Larry']])let val = nulllet tmp = 'Apple'      for (const [key, value] of map) {        if (tmp == key) {          val = value        }}

原文 本人又补充了一个 :https://segmentfault.com/a/11...