JavaScript条件语句优化

1. 三元运算符

<div v-for="(item, index) in drugList" :key="index" @click="loadPage(item)">
    // ...
</div>

loadPage(item) {
  if(item.type==='SHOP_DRUG') {
    this.loadPageShopDrugs(item.id);
  } else {
    this.loadPageDrugsShops(item.drugId);
  }
}

// after...
<div v-for="(item, index) in drugList" :key="index" @click="item.type==='SHOP_DRUG' ? loadPageShopDrugs(item.id) : loadPageDrugsShops(item.drugId)">
    // ...
</div>

2. Array.includes 

if(type == 1 || type == 2 || type == 3 || type == 4){
   // ......
}

// after...
let list = [1,2,3,4]; 
if(list.includes(type)){
   // ......
}

3. 可选链和空值合并操作符

car = {
    model: 'Fiesta',
    manufacturer: {
      name: 'Ford',
      address: {
        street: 'Some Street Name',
        number: '5555',
        state: 'USA'
      }
    }
}

// 可选链式操作符(?.):访问属性可能为 undefined 与 null 的对象时,返回右侧
if(car && car.manufacturer && car.manufacturer.address && car.manufacturer.address.state === 'USA') {
  console.log('true');
}

// after:
if(car?.manufacturer?.address?.state === 'USA') {
  console.log('true');
}


// 空值合并运算符(??) :当左侧为 null 或者 undefined 时,返回右侧(0, '', NaN会被返回)
const street = car && car.manufacturer && car.manufacturer.address && car.manufacturer.address.street || 'default street';

// after:
const street = car?.manufacturer?.address?.street ?? 'default street';

4. 默认参数和解构

test(object) { 
    if (object && object.name) {
     console.log (object.name);
   } else {
    console.log('unknown');
   }
}

// after....
test({name} = {}) {
   console.log (name || 'unknown');
}

5. Array.every & Array.some

Array.every 方法检查数组中的所有项是否满足某个条件
Array.some() 方法检查数组中的一个元素来满足某个条件

list = [
  {shopName: 'xx人民路店', state: 'normal'},
  {shopName: 'xx大药房', state: 'rest'},
  {shopName: 'xx医药连锁', state: 'check'},
]

const isNormal = list.every(f => f.state == 'normal');
console.log(isNormal); // false

const isNormal = list.some(f => f.state == 'normal');
console.log(isNormal); // true

6. 提前return

示例一:

if (object) {
  if (object.type) {
    if (object.name) {
      if (object.gender) {
        result = ${object.name} is a ${object.gender} ${object.type};;
      } else {
        result = "No object gender";
      }
    } else {
      result = "No object name";
    }
  } else {
    result = "No object type";
  }
} else {
  result = "No object";
}

// after...
const test = ({type, name, gender } = {}) => {
  if(!type) return 'No object type';
  if(!name) return 'No object name';
  if(!gender) return 'No object gender';
  return ${name} is a ${gender} ${type};
}
test({ type: 'admin', name: 'zs', gender: 'female' })

示例二:

test(type, number) {
  const types = [1,2,3,4,5,6,7,8,9];
   if (type) {
     if (types.includes(type)) {
       // ...
       if (number >= 100) {
		  // ...
       }
     }
   } else {
     throw new Error('empty'); // 创造一个错误类型抛出
   }
}

// after...
test(type, number) {
  const types = [1,2,3,4,5,6,7,8,9];
  if (!type) throw new Error('empty');
  if (!types.includes(type)) return;
  if (number >= 100) {
    // ...
  }
}

7. 对象字面量或Map替代Switch

convertStatus (status) {
  switch (status) {
    case 'normal':
      return '正常'
    case 'rest':
      return '停业'
    case 'violation':
      return '违规'
    case 'check':
      return '待审核'
    case 'fail':
      return '未通过'
     default:
      return '';
  }
}


// 对象字面量:
const statusObj= {
  normal: '正常',
  rest: '停业',
  violation: '违规',
  check: '待审核',
  fail: '未通过',
};

convertStatus(status) {
  return statusObj[status] || '';
}

// Map:
const obj = new Map()
obj.set('normal', '正常')
obj.set('rest', '停业')
obj.set('violation', '违规')
obj.set('check', '待审核')
obj.set('fail', '未通过')

convertStatus(status) {
  return statusObj.get(status) || '';
}

。。。。。。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值