使用对象代替复杂的if else,switch case

Posted 铁锤妹妹@

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了使用对象代替复杂的if else,switch case相关的知识,希望对你有一定的参考价值。

以前多条件判断都是if…else 或者 switch…case

 filterSign(val) 
      if (val === 0) 
        //0待签到 1已签到 2漏签
        return `$this.imgBaseUrlmine/sign_waiting.png`
       else if (val === 1) 
        return `$this.imgBaseUrlmine/sign_checked.png`
       else if (val === 2) 
        return `$this.imgBaseUrlmine/sign_not_checked.png`
      
    

后来发现用对象key,value也不失为一种好办法

 filterSign(val) 
      let obj = 
        0: this.imgBaseUrl + 'mine/sign_waiting.png',
        1: this.imgBaseUrl + 'mine/sign_checked.png',
        2: this.imgBaseUrl + 'mine/sign_not_checked.png',
      
      return obj[val]
    ,

以上是关于使用对象代替复杂的if else,switch case的主要内容,如果未能解决你的问题,请参考以下文章