优化js高频判断,提高可读性,摘要

一些js的高频优化

优化if -else
const isBabyPet = (pet, age) => {
  if (pet) {
    if (isPet(pet)) {
      console.log(‘It is a pet!’);
      
      if (age < 1) {
        console.log(‘It is a baby pet!’);
      }
    } else {
      throw new Error(‘Not a pet!’);
    }
  } else {
    throw new Error(‘Error!’);
  }
};
编写代码比较繁琐,使用高质量代码省去空间,提高代码可读性
const isBabyPet = (pet, age) => {
  if (!pet) throw new Error(‘Error!’);
  if (!isPet(pet)) throw new Error(‘Not a pet!’);
  
  console.log(‘It is a pet!’);
  if (age < 1) {
    console.log(‘It is a baby pet!’);
  }
};

使用Array.includes

const isPet = animal => {
  if (animal === ‘cat’ || animal === ‘dog’) {
    return true;
  }
  
  return false;
};

//优化
const isPet = animal => {
  const pets = [‘cat’, ‘dog’, ‘snake’, ‘bird’];
  
  return pets.includes(animal);
};

Array.some/every/filter

const fileList=[
    {fileType:15,fileUrl:'555555555555'},
    {fileType:14,fileUrl:'777777777777'}
]
let isType=fileList.some(item=>{
			//条件: 是否存在符合条件数据
      return item.fileType===15
})

const fileList=[
    {fileType:15,fileUrl:'555555555555'},
    {fileType:14,fileUrl:'777777777777'}
] 
function test() {
   // 条件:简短方式,所有数据都必须是15
   const isAllRed = fileList.every(f => f.fileType === 15);
   console.log(isAllRed); // false
}
 
const fileList=[
    {fileType:15,fileUrl:'555555555555'},
    {fileType:14,fileUrl:'777777777777'}
]
function test(color) {
   // 条件:过滤符合条件数据 
   return fileList.filter(f => f.fileType === 15);
}

用索引代替switch-case
const getBreeds = pet => {
  switch (pet) {
    case ‘dog’:
      return [‘Husky’, ‘Poodle’, ‘Shiba’];
    case ‘cat’:
      return [‘Korat’, ‘Donskoy’];
    case ‘bird’:
      return [‘Parakeets’, ‘Canaries’];
    default:
      return [];
  }
};
let dogBreeds = getBreeds(‘dog’); //[“Husky”, “Poodle”, “Shiba”]
优化后可精简,提高可读
const breeds = {
  ‘dog’: [‘Husky’, ‘Poodle’, ‘Shiba’],
  ‘cat’: [‘Korat’, ‘Donskoy’],
  ‘bird’: [‘Parakeets’, ‘Canaries’]
};
const getBreeds = pet => {
  return breeds[pet] || [];
};
let dogBreeds = getBreeds(‘cat’); //[“Korat”, “Donskoy”]
摘要部分文档,提高可阅读性,提高coding
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值