1 - 多个if、else if条件判断优化

367 阅读1分钟

判断的条件比较多的时候,使用多个if判断代码可读性较差,也不易于维护;所以,可以使用对象、数组、map等形式去优 化:

一、 单个if多条件优化

1. 单个if多条件:

function weather(type) {
  if (type === '小雨' || type === '中雨' || type === '大雨' || type === '暴雨') {
    console.log("今天是雨天");
  }
}

2. 单个if多条件优化后:

function weather(type) {
  const imgArr = ['小雨', '中雨', '大雨', '暴雨']
  if (imgArr.includes(type)) {
    console.log("今天是雨天");
  }
}

二、多个else if分支优化:

1. 多个else if分支:

let weather = '晴1';
function weatherImg() {
  if (weather === '晴') {
    return 'sun.png';
  } else if (weather === '小雨' || weather === '中雨' || weather === '大雨' || weather === '暴雨') {
    return "rain.png";
  } else {
    return "xx.png";
  }
}
console.log('优化前打印结果:', weatherImg()) //xx.png

2. 多个else if分支使用对象的key-value形式来实现:

let weatherArray = {
  '晴': 'sun.png',
  '小雨|中雨|大雨|暴雨': 'rain.png',
}

function weatherImage(weatherArray) {
  const res = {}
  Object.entries(weatherArray).forEach(([key, value]) => {
    const keyArr = key.split('|');
    console.log('keyArr', keyArr)
    keyArr.forEach(item => {
      res[item] = value
    })
  })
  console.log('res', res);
  return res;
}


const weatherMap = weatherImage(weatherArray)
console.log('weatherMap', weatherMap[weather] ? weatherMap[weather] : 'xx.png'); //xx.png

3. 多个else if分支使用数组对象形式来实现:

function weatherImg1() {
  const weatherArray = [{
      filter: (weather) => weather === '晴',
      image: 'sun.png',
    },
    {
      filter: (weather) => {
        const filterArr = [
          "小雨",
          "中雨",
          "大雨",
          "暴雨",
        ];
        return filterArr.includes(weather);
      },
      image: "rain.png",
    },
  ];
  const filterMap = (weather) => {
    //find()方法返回通过测试(函数内判断)的数组的第一个元素的值
    const filterMapItem = weatherArray.find((item) => item.filter(weather));
    if (!filterMapItem) {
      return '';
    }
    return filterMapItem.image;
  };
  return filterMap(weather) ? filterMap(weather) : "xx.png";
}
console.log('优化后打印结果:', weatherImg1()) //xx.png

二、多个else if分支,单一条件的优化:

1. 多个else if分支,单一条件:

function handleA() {
  console.log('handleA');
}

function handleB() {
  console.log('handleBB');
}

function handleC() {
  console.log('handleC');
}

if (this.type === 'A') {
  handleA();
} else if (this.type === 'B') {
  handleB();
} else if (this.type === 'C') {
  handleC();
}

2. 多个else if分支,单一条件使用map优化:

var enums = new Map([
  ['A', handleA],
  ['B', handleB],
  ['C', handleC],
])

function handleFn(val) {
  let handleType = enums.get(val);
  handleType()
}

handleFn('A'); //handleA