接到这个需求就开始把每个变量都声明了一遍,就造成了臃肿多重复的代码了,看!

if (this.formConfig.timeRulesArr[0].time[0] != '') {
//重复1,声明了9个变量
        let isCalendarList00 = true
        let isCalendarList01 = true
        let isCalendarList02 = true
        let isCalendarList03 = true
        let isCalendarList04 = true
        let isCalendarList05 = true
        let isCalendarList06 = true
        let isCalendarList07 = true
        let isCalendarList08 = true
        this.formConfig.timeRulesArr.forEach((item, index) => {
          let isCalendarState = true
          if (item.time[0] && item.time[1]) {
            isCalendarState =
              moment(new Date(item.time[0])) > current ||
              moment(new Date(item.time[1])).add(1, 'd') < current
          }
        //重复2,遍历了index每个都重新赋值
          switch (index) {
            case 0:
              isCalendarList00 = isCalendarState
              break
            case 1:
              isCalendarList01 = isCalendarState
              break
            case 2:
              isCalendarList02 = isCalendarState
              break
            case 3:
              isCalendarList03 = isCalendarState
              break
            case 4:
              isCalendarList04 = isCalendarState
              break
            case 5:
              isCalendarList05 = isCalendarState
              break
            case 6:
              isCalendarList06 = isCalendarState
              break
            case 7:
              isCalendarList07 = isCalendarState
              break
            case 8:
              isCalendarList08 = isCalendarState
              break
          }
        })
        //重复3,把每个变量都依次返回
        return (
          isCalendarList00 &&
          isCalendarList01 &&
          isCalendarList02 &&
          isCalendarList03 &&
          isCalendarList04 &&
          isCalendarList05 &&
          isCalendarList06 &&
          isCalendarList07 &&
          isCalendarList08
        )
      }
     
     

用new Map()优化代码,如下

if (this.formConfig.timeRulesArr[0].time[0] != '') {
//1,用new Map()存储每一个变量,并初始赋值
        let mCalendar = new Map()
        for (let i = 0; i < 9; i++) {
          mCalendar.set('isDis' + i, true)
        }
        this.formConfig.timeRulesArr.forEach((item, index) => {
          let isCalendarState = true
          if (item.time[0] && item.time[1]) {
            isCalendarState =
              moment(new Date(item.time[0])) > current ||
              moment(new Date(item.time[1])).add(1, 'd') < current
          }
         //2,set重新赋值
          mCalendar.set('isDis' + index, isCalendarState)
        })
        //3,通过forEach遍历拿到item值
        let isSureDis = true
        mCalendar.forEach(function(item, key, mapObj) {
          console.log(item, key, mapObj)
          if (!item) {
            isSureDis = false
          }
        })
        return isSureDis
      }
      
      

new Map()用法参考文章,https://blog.csdn.net/z937010...


我在神游
18 声望3 粉丝