if - else优化处理

最近在思否上看到这么一个问答,多个if的写法如何优化,如下

statusText(value) {
      if (value === '0') {
        return '你好'
      }
      if (value === '1') {
        return '我好'
      }
      if (value === '2') {
        return '他好'
      }
      if (value === '3') {
        return '大家好'
      }
      if (value === '4') {
        return '你不好'
      }
      if (value === '5') {
        return '我不好'
      }
     }

经典的回复

fucntion statusText(value){
    return ['你好', '我好', '大家好', '你不好', '我不好'][value]
}

很是不错,于是看了看自己项目中的一些代码,发现如下面一段臃肿的代码

 disType(nv) {
      let allfx = document.querySelectorAll('.fx')
      let allyh = document.querySelectorAll('.yh')
      let allzy = document.querySelectorAll('.zy')

      if (nv == 'fx') {
        this.showType = 1
        allfx.forEach((fx) => {
          fx.style.display = 'block'
        })
        allyh.forEach((yh) => {
          yh.style.display = 'none'
        })
        allzy.forEach((zy) => {
          zy.style.display = 'none'
        })
      } else if (nv == 'yh') {
        this.showType = 2
        allfx.forEach((fx) => {
          fx.style.display = 'none'
        })
        allyh.forEach((yh) => {
          yh.style.display = 'block'
        })
        allzy.forEach((zy) => {
          zy.style.display = 'none'
        })
      } else if (nv == 'zy') {
        this.showType = 3
        allfx.forEach((fx) => {
          fx.style.display = 'none'
        })
        allyh.forEach((yh) => {
          yh.style.display = 'none'
        })
        allzy.forEach((zy) => {
          zy.style.display = 'block'
        })
      }
    }

这段代码要做的就是,取到页面上所有类名为 fx,yh,和zy的元素,根据这个函数传进来的参数nv,来控制类名为 fx,yh,和zy元素的display属性从而控制显隐,另外设置this.showType的值优化处理后,如下

disType(nv) {
      let types = ['fx', 'yh', 'zy']
      types.forEach((type) => {
        document.querySelectorAll('.' + type).forEach((ele) => {
          ele.style.display = type == nv ? 'block' : 'none'
        })
      })
      this.showType = types.indexOf(nv) + 1
    },

大家有什么更好 的优化方案随时留言,感谢

javascript
46 views
Comments
登录后评论
Sign In
·

普通逻辑可以 switch + enum 或者策略模式优化一下,高频访问语句还是保留 if-else,这种原始语句有利于编译器优化(分支预测)