持续创作,加速成长!这是我参与「掘金日新计划 · 10 月更文挑战」的第14天,点击查看活动详情
前言
代码重构是必不可少的,下面我将分享几个js代码的简化与重构,希望对大家有所帮助同时欢迎讨论指出问题!
1.判断空字符串,null
null,空字符,undefine, 0, NaN, '' 判断时返回false; ' ' , 判断时返回false(空格 属于非空字符) 非空字符 作布尔运算时,都会返回 true
不好的写法
if (value !== "") {
//do something...
}
优化的写法
if (value) {
//do something...
}
2.if简写
不好的写法:这种写法啰嗦切不美观
if (this.age > 20) {
this.ageReturn = true;
} else {
this.ageReturn = false;
}
优化的写法:简单明了的输出了想要的结果,还节省了代码量
this.ageReturn = this.age > 20;
3.map优化 if else, 或switch
不好的写法:这种方法代码过多,太冗余繁杂
function changeType(type){
if(type === 1){
return '苹果'
}else if(type === 2){
return '香蕉'
}else if(type === 3){
return '草莓'
}
}
优化的写法 1.方法一:使用map优化
function changeType(type){
let typeMap = new Map([
[1, '苹果'],
[2, '香蕉'],
[3, '草莓'],
]);
return typeMap.get(type)
}
- 方法二:对象 key-value映射关系 优化
function changeType(type){
let typeMap ={
1: '苹果',
2: '香蕉',
3: '草莓',
};
return typeMap[type]
}
4.if else 简化
不好的写法:这种写法嵌套太多,不美观,一看见就脑袋疼,而且容易出错
if (this.isDead) {
return this.deadAmount();
} else {
if (this.isSeparated) {
return this.separatedAmount();
} else {
if (this.isRetired) {
return this.retiredAmount();
} else {
return this.normalPayAmount();
}
}
}
优化的写法:改为平行关系,而非包含关系
if (this.isDead) return this.deadAmount();
if (this.isSeparated) return this.separatedAmount();
if (this.isRetired) return this.retiredAmount();
return this.normalPayAmount();
4.交换变量
不好的写法:
let x = 'Hello', y = 55;
const temp = x;
x = y;
y = temp;
优化的写法:直接使用Es6的结构赋值来解决问题简单明了
let x = 'Hello', y = 55;
[x, y] = [y, x];
结束语
希望大家能够喜欢我的文章,我真的很用心在写,也希望通过文章认识更多志同道合的朋友。
最后伙伴们,如果喜欢我的可以给点一个小小的赞👍或者关注➕都是对我最大的支持。