25 条示例代码让你的代码更简洁

JavaScript 无处不在,从 PC 端到移动设备端,甚至是后端,都在使用 JavaScript。

在本文中,我将尝试一些可用来使代码看起来更简洁的实践方案。

1、使用默认参数代替短路或条件

默认参数通常比短路更简洁。

1
2
3
4
5
6
7
function SomeMethod(paramThatCanBeUndefined) {
const localValue = paramThatCanBeUndefined || "Default Value";
console.log(localValue);
// ...
}
SomeMethod(); // Default Value
SomeMethod("SomeValue"); // SomeValue

尝试以下方法:

1
2
3
4
5
6
function SomeMethod(
console.log(paramThatCanBeUndefined)
// ...
}
SomeMethod() // Default Value
SomeMethod("SomeValue") // SomeValue

声明:Falsy 值,如’’,””,false,null,0,和 NaN 将不会被默认值替代:

1
2
3
4
5
6
function SomeMethod(paramThatCanBeUndefined = "Default Value") {
console.log(paramThatCanBeUndefined);
// ...
}
SomeMethod(null); // will not Default Value, will null Instead
SomeMethod("SomeValue"); // SomeValue

2、处理多个条件

1
2
3
4
5
6
7
8
const conditions = ["Condition 2","Condition String2"];
someFunction(str){
if(str.includes("someValue1") || str.includes("someValue2")){
return true
}else{
return false
}
}

一种更简洁的方法是:

1
2
3
4
someFunction(str){
const conditions = ["someValue1","someValue2"];
return conditions.some(condition=>str.includes(condition));
}

3、用动态键值对替换开关(即对象文字)

开关版本(或将开关替换为 if / else):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
const UserRole = {
ADMIN: "Admin",
GENERAL_USER: "GeneralUser",
SUPER_ADMIN: "SuperAdmin",
};
function getRoute(userRole = "default role") {
switch (userRole) {
case UserRole.ADMIN:
return "/admin";
case UserRole.GENERAL_USER:
return "/GENERAL_USER";
case UserRole.SUPER_ADMIN:
return "/superadmin";
default:
return "/";
}
}
console.log(getRoute(UserRole.ADMIN)); // return "/admin"
console.log(getRoute("Anything")); // return Default path
console.log(getRoute()); // return Default path
console.log(getRoute(null)); // return Default path

// More cases if new arrive
// You can think if else instead of switch

动态键值对版本:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
const UserRole = {
ADMIN: "Admin",
GENERAL_USER: "GeneralUser",
SUPER_ADMIN: "SuperAdmin",
};
function getRoute(userRole = "default role") {
const appRoute = {
[UserRole.ADMIN]: "/admin",
[UserRole.GENERAL_USER]: "/user",
[UserRole.SUPER_ADMIN]: "/superadmin",
};
return appRoute[userRole] || "Default path";
}
console.log(getRoute(UserRole.ADMIN)); // return "/admin"
console.log(getRoute("Anything")); // return Default path
console.log(getRoute()); // return Default path
console.log(getRoute(null)); // return Default path
// No more switch/if-else here.
// Easy to Further expansion

4、避免过多的函数参数

1
2
3
4
5
6
7
8
9
10
11
function myFunction(employeeName, jobTitle, yrExp, majorExp) {
return `${employeeName} is working as ${jobTitle} with ${yrExp} years of experience in ${majorExp}`;
}
//output be like John is working as Project Manager with 12 year of experience in Project Management
// you can call it via
console.log(myFunction("John", "Project Manager", 12, "Project Management"));
// ***** PROBLEMS ARE *****
// Violation of 'clean code' principle
// Parameter sequencing is important
// Unused Params warning if not used
// Testing need to consider a lot of edge cases.

这是一种更清洁的方法:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
function myFunction({ employeeName, jobTitle, yrExp, majorExp }) {
return `${employeeName} is working as ${jobTitle} with ${yrExp} years of experience in ${majorExp}`;
}
//output be like John is working as Project Manager with 12 year of experience in Project Management
// you can call it via
const mockTechPeople = {
employeeName: "John",
jobTitle: "Project Manager",
yrExp: 12,
majorExp: "Project Management",
};
console.log(myFunction(mockTechPeople));
// ES2015/ES6 destructuring syntax is in action
// map your desired value to variable you need.

5、使用 Object.assign 设置默认对象

这看起来很繁琐:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
const someObject = {
title: null,
subTitle: "Subtitle",
buttonColor: null,
disabled: true,
};
function createOption(someObject) {
someObject.title = someObject.title || "Default Title";
someObject.subTitle = someObject.subTitle || "Default Subtitle";
someObject.buttonColor = someObject.buttonColor || "blue";
someObject.disabled =
someObject.disabled !== undefined ? someObject.disabled : true;
return someObject;
}
console.log(createOption(someObject));

// Output be like
// {title: 'Default Title', subTitle: 'Subtitle', buttonColor: 'blue', disabled: true}

这种方法看起来更好:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
const someObject = {
title: null,
subTitle: "Subtitle",
buttonColor: null,
disabled: true,
};
function creteOption(someObject) {
const newObject = Object.assign(
{
title: "Default Title",
subTitle: "Default Subtitle",
buttonColor: "blue",
disabled: true,
},
someObject
);
return newObject;
}
console.log(creteOption(someObject));

6.通过条件判断给变量赋值布尔值的正确姿势

1
2
3
4
5
6
7
8
9
// bad
if (a === "a") {
b = true;
} else {
b = false;
}

// good
b = a === "a";

7.在 if 中判断数组长度不为零的正确姿势

1
2
3
4
5
6
7
8
9
// bad
if (arr.length !== 0) {
// todo
}

// good
if (arr.length) {
// todo
}

8.同理,在 if 中判断数组长度为零的正确姿势

1
2
3
4
5
6
7
8
9
// bad
if (arr.length === 0) {
// todo
}

// good
if (!arr.length) {
// todo
}

9.简单的 if 判断使用三元表达式

1
2
3
4
5
6
7
8
9
// bad
if (a === "a") {
b = a;
} else {
b = c;
}

// good
b = a === "a" ? a : c;

10.使用 includes 简化 if 判断

1
2
3
4
5
6
7
8
9
10
// bad
if (a === 1 || a === 2 || a === 3 || a === 4) {
// todo
}

// good
let arr = [1, 2, 3, 4];
if (arr.includes(a)) {
// todo
}

巧用数组方法,尽量避免用 for 循环

11.使用 some 方法判断是否有满足条件的元素

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// bad
let arr = [1, 3, 5, 7];
function isHasNum(n) {
for (let i = 0; i < arr.length; i++) {
if (arr[i] === n) {
return true;
}
}
return false;
}

// good
let arr = [1, 3, 5, 7];
let isHasNum = (n) => arr.some((num) => num === n);

// best
let arr = [1, 3, 5, 7];
let isHasNum = (n, arr) => arr.some((num) => num === n);

12.使用 forEach 方法遍历数组,不形成新数组

1
2
3
4
5
6
7
8
9
10
11
// bad
for (let i = 0; i < arr.length; i++) {
// todo
arr[i].key = balabala;
}

// good
arr.forEach((item) => {
// todo
item.key = balabala;
});

13.使用 filter 方法过滤原数组,形成新数组

1
2
3
4
5
6
7
8
9
10
11
12
// bad
let arr = [1, 3, 5, 7],
newArr = [];
for (let i = 0; i < arr.length; i++) {
if (arr[i] > 4) {
newArr.push(arr[i]);
}
}

// good
let arr = [1, 3, 5, 7];
let newArr = arr.filter((n) => n > 4); // [5, 7]

14.使用 map 对数组中所有元素批量处理,形成新数组

1
2
3
4
5
6
7
8
9
10
// bad
let arr = [1, 3, 5, 7],
newArr = [];
for (let i = 0; i < arr.length; i++) {
newArr.push(arr[i] + 1);
}

// good
let arr = [1, 3, 5, 7];
let newArr = arr.map((n) => n + 1); // [2, 4, 6, 8]

巧用对象方法,避免使用 for…in

15.使用 Object.values 快速获取对象键值

1
2
3
4
5
6
7
8
9
10
11
12
let obj = {
a: 1,
b: 2,
};
// bad
let values = [];
for (key in obj) {
values.push(obj[key]);
}

// good
let values = Object.values(obj); // [1, 2]

16.使用 Object.keys 快速获取对象键名

1
2
3
4
5
6
7
8
9
10
11
12
let obj = {
a: 1,
b: 2,
};
// bad
let keys = [];
for (value in obj) {
keys.push(value);
}

// good
let keys = Object.keys(obj); // ['a', 'b']

巧用解构简化代码

17.解构数组进行变量值的替换

1
2
3
4
5
6
7
8
9
10
// bad
let a = 1,
b = 2;
let temp = a;
a = b;
b = temp;

// good
let a = 1,
b = ((2)[(b, a)] = [a, b]);

18.解构对象

1
2
3
4
5
6
7
8
9
10
11
12
13
// bad
setForm (person) {
this.name = person.name
this.age = person.age
}

// good
setForm ({name, age}) {
this.name = name
this.age = age
}


19.解构时重命名简化命名

有的后端返回的键名特别长,你可以这样干

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// bad
setForm (data) {
this.one = data.aaa_bbb_ccc_ddd
this.two = data.eee_fff_ggg
}
// good
setForm ({aaa_bbb_ccc_ddd, eee_fff_ggg}) {
this.one = aaa_bbb_ccc_ddd
this.two = eee_fff_ggg
}

// best
setForm ({aaa_bbb_ccc_ddd: one, eee_fff_ggg: two}) {
this.one = one
this.two = two
}


20.解构时设置默认值

1
2
3
4
5
6
7
8
9
10
11
12
13
14
// bad
setForm ({name, age}) {
if (!age) age = 16
this.name = name
this.age = age
}

// good
setForm ({name, age = 16}) {
this.name = name
this.age = age
}


21.||短路符设置默认值

1
2
3
4
5
6
let person = {
name: "张三",
age: 38,
};

let name = person.name || "佚名";

22.&&短路符判断依赖的键是否存在防止报错’xxx of undfined’

1
2
3
4
5
6
7
8
9
let person = {
name: "张三",
age: 38,
children: {
name: "张小三",
},
};

let childrenName = person.children && person.childre.name;

23.字符串拼接使用${}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
let person = {
name: 'LiMing',
age: 18
}
// bad
function sayHi (obj) {
console.log('大家好,我叫' + person.name = ',我今年' + person.age + '了')
}

// good
function sayHi (person) {
console.log(`大家好,我叫${person.name},我今年${person.age}了`)
}

// best
function sayHi ({name, age}) {
console.log(`大家好,我叫${name},我今年${age}了`)
}


24.函数使用箭头函数

1
2
3
4
5
6
7
8
9
10
11
12
let arr [18, 19, 20, 21, 22]
// bad
function findStudentByAge (arr, age) {
return arr.filter(function (num) {
return num === age
})
}

// good
let findStudentByAge = (arr, age)=> arr.filter(num => num === age)


25.函数参数校验

1
2
3
4
5
6
7
8
9
10
11
12
// bad
let findStudentByAge = (arr, age) => {
if (!age) throw new Error("参数不能为空");
return arr.filter((num) => num === age);
};

// good
let checkoutType = () => {
throw new Error("参数不能为空");
};
let findStudentByAge = (arr, age = checkoutType()) =>
arr.filter((num) => num === age);

欢迎大佬们指正交流,感谢支持