js 条件判断踩坑(一)

135 阅读1分钟

提前返回,少用if...else

  • 缺: 典型的条件嵌套--分支语句导致过多嵌套
function func () {
  var res = '';
  if (conditionA) {
    if (conditionB) {
      res = 'Success';
    } else {
     res = 'Err1';
    }
  else {
    res = 'Err2';
  }
  return res;
};
  • 优: 在if里做非判断--条件反转,并通过卫语句提前return else 分支
  function func () {
    if (!conditionA) {
      return 'Err2';
    }
    if (!conditionB) {
      return 'Err1';
    }
    return 'Success';
  }

forEach 优化

  • 缺:遍历的时候也经常产生大量的嵌套。如下,先对数组元素做一次合法性校验,通过后再做一次新的操作,最后把结果追加到新数组里。
  const fun = (arr) => {
    const res = [];
    arr.forEach( e => {
      if(e !== '0') {
        res.push(`${e}`}
      }
    })
    return res;
  }
        
  • 优: 函数式编程
  const func = (arr) => {
    return arr;
    .filer( e => e !== '0');
    .map( e => `${e}`);
  }

多条件,用Array.includes

  • 缺: 例如某个页面需要检验输入type是否合法。
  const init (type) {
    if (type === 'A' || type === 'B'){
      console.log('ok')
    }
    ...
    console.log('err')
  }
  • 优: 把非法类型存到数组里,用Array.incloudes完成冗长的判断,之后每增加一种新的类型,只需在数组后追加新的字符串。
  const init (type) {
    const invalidArr = ['A', 'B', 'C'];
    if (invalidArr.incloudes(type)){
      console.log('ok')
    }
    ...
  };

使用Object索引

  • 缺: 类似情况也出现在三元表达式里
  const date = (dateTime) => {
    const format = this.$i18n.locale === 'en' ? 'mmm d, yyyy' : 'yyyy年m月d日';
    return date(dateTime, format);
  }
  • 优: 多语言时,使用Object键索引
const localeFormats = {
  en: 'mmm d, yyyy',
  zh: 'yyyy年m月d日',
  ja: 'yyyy/m/d',
};
const date = localeFormats[this.$i18n.locale];

尽量少用switch

  • 缺: 长switch
  export function (type) {
    switch(type) {
      case 'A':
        return fun1();
      case 'B':
        return fun2();
      case 'C':
        return fun3();
      default:
        return fun4();
    }
  }
  
        
  • 优: OOP设计模式:尽量使用多态和继承代替Switch结构。JS:可以用Object或Map索引代替Switch。
  const arr = [
    ['A', fun1],
    ['B', fun2],
    ['C', fun3],
  ];
  const deffFun = () => {
   console.error('Error');
  };
  const carryFun = new Map(arr);
  export function (type) {
    return ( carryFun.get(type) || deffFun).call(null);
  };

Optional Chaining

  • Optional Chaining(以下简称OC)-语法糖,ECMAScript stage2。
//多层嵌套
  // 一层:
  if (address) {
    var street = address.street;
  }
  // 两层
  if (basicInfo) {
    var address= basicInfo.address;
    if (address) {
      var street = address.street;
    }
  }
  // n层....
  ....
  // OC语法糖
  var street = basicInfo?.address?.street;