如何把js写得更漂亮

分类:技术来源:bobo最近更新:2022-11-09浏览:1447

如何把js写得更漂亮

每次评审之前自己或者小伙伴的代码时,都忍不住的想吐槽一些代码,今天有空梳理一下,如何让自己的代码写得更漂亮。

1、从对象中取值,设置默认值时

const obj={a:1,b:2,c:3}
// 从对象中取值,并计算时
// 吐槽
const a = obj.a;
const b = obj.b;
const c = obj.c;
const f=a+b+c;

// 修改 =>采用ES6解构
const {a,b,c} = obj;
// 如果从后端取值,不是自己想要的键值,可以设置别名,同时要防止后端返回的不是对象
const {a:_a,b,c}=obj||{};

2、数组的合并

const a = [1,2,3];
const b = [1,5,6];
// 在ES6之前,我们习惯用concat
const c=a.concat(b);
// 可以采用ES6
const c= [...a,...b]
// 如果考虑去重
const c = [...new Set([...a,...b])];

3、if中多个条件判断

// 吐槽
if(
type == 1 ||
type == 2 ||
type == 3 ||
type == 4 ||
)
// 优化
const condition = [1,2,3,4];
if( condition.includes(type) )

4、关于数组filter和find。如果可以断定,查找的结果最多一个,建议用find,因为find检索到就退出循环了。

**5、对象的&&关系 **

// 吐槽
const name = obj && obj.name;
// 优化
const name = obj?.name;

6、输入框中非空的判断

// 吐槽
if(value !== null && value !== undefined && value !== '')
// 优化
if((value??'') !== '')

7、有意义和无意义的事

// 1、画手添足定义变量
const len=8;
if(a10不就是true,干嘛还要这样判断
let test = x > 10 ? true : false;
if(test)

// 优化
if(x>10)

9、开关的简化

// 吐槽
switch (data) {
case 1:
test1();
break;
case 2:
test2();
break;
case 3:
test();
break;
//...
}

// 优化
const data=[test1,test2,test3]
data[type-1] && data[type-1]();

10、indexOf的按位化简(不怎么建议用,因为可读性太差了,一句个人习惯,往往incluce最好)

// 原本
if (arr.indexOf(item) > -1) {
// item found
}
if (arr.indexOf(item) === -1) {
// item not found
}
// 优化
if (~arr.indexOf(item)) {
// item found
}
if (!~arr.indexOf(item)) {
// item not found
}