一些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