从6个方面净化你的Js代码
web前端开发
共 1854字,需浏览 4分钟
·
2020-11-25 02:53
Grady booch:简单直接
Dave thomas:可读,可维护,单元测试
Ron Jeffries:不要重复、单一职责,表达力(Expressiveness)
1、注重命名
function mergeNumberListIntoUniqueList(listOne, listTwo) {
return [...new Set([...listOne, ...listTwo])]
}
function mergeLists(listOne, listTwo) {
return [...listOne, ...listTwo]
}
function createUniqueList(list) {
return [...new Set(list)]
}
2、IF语句简化
if(value === 'duck' || value === 'dog' || value === 'cat') {
// ...
}
const options = ['duck', 'dog', 'cat'];
if (options.includes(value)) {
// ...
}
3、及早返回
function handleEvent(event) {
if (event) {
const target = event.target;
if (target) {
// Your awesome piece of code that uses target
}
}
}
function handleEvent(event) {
if (!event || !event.target) {
return;
}
// Your awesome piece of code that uses target
}
4、解构赋值
// object 解构赋值
const numbers = {one: 1, two: 2};
const {one, two} = numbers;
console.log(one); // 1
console.log(two); // 2
// array 解构赋值
const numbers = [1, 2, 3, 4, 5];
const [one, two] = numbers;
console.log(one); // 1
console.log(two); // 2
5、童子军规则
6、代码风格
评论