

如何编写干净的JavaScript代码?
source link: https://www.fly63.com/article/detial/11672
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

今天来分享几个编写干净的JavaScript代码的技巧!
1. 更好的命名
在 JavaScript 中,良好命名的关键不在于最短的变量名,而在于最具描述性的变量名。
(1)减少幻数
将代码中的一些数字定义为一个常量,以使它更有意义,也便于后期的维护。
for (i=0; i < 8765; i++){}
:white_check_mark:
const HOURS_IN_A_YEAR = 8765
for (i=0; i < HOURS_IN_A_YEAR; i++){}
(2)语义化命名
尽可能语义化变量和函数的名称。
onst expired = true;
const e = true;
:white_check_mark:
const hasExpired = true; // 布尔值应该有一个类似于is、has或was的前缀
const expiredDate = new Date()
let expiredElementsAmount = 0
let allExpiredElemnts = []
2. 保持简洁
(1)避免重复
为了更好地实现简洁的代码,应该遵循DRY(Don't Repeat Yourself)原则。减少代码的重复。
async function notifyUsers(userIds, message) {
userIds.foreach(userId => {
const user = await User.findByPk(userId)
if(user.isSubscribed) {
const Notification = await Notifications.create({
date: new Date(),
user_id: userId,
message,
emailNotify: true });
Notification.save();
} else {
const Notification = await Notifications.create({
date: new Date(),
user_id: userId,
message,
emailNotify: true });
Notification.save();
}
}
}
:white_check_mark:
async function notifyUsers(userIds, message) {
userIds.foreach(userId => {
const user = await User.findByPk(userId)
notifyUsers(userId, message, user.isSubscribed)
}
}
async function createNotification(userId, message, isSubscribed) {
const Notification = await Notifications.create({
date: new Date(),
user_id: userId,
message,
emailNotify: isSubscribed });
Notification.save();
}
(2)使用递归
有些情况下,使用递归的代码会比迭代更加简洁。
const stepsToHundred = (number) => {
let steps = 0
while(number < 100) {
number *= 2
steps++
}
return steps
}
:white_check_mark:
const stepsToHundred = (number, steps) =>
number < 100 ? stepsToHundred(number * 2, steps + 1) : steps
(3)字符串连接
ES6中新增了模板字符串功能使我们可以在拼接字符串时代码更短、更简洁。
:white_check_mark:
const welcomeMessage = "你好" + user1 + ", 我是" + user2;
const welcomeMessage = `你好 ${user1}, 我是 ${user2}`
3. 减少多层嵌套
(1)条件语句
不要将 return 语句嵌套到 if-else 中。
const getUSTime = (time) => {
if(time <= 12){
return time + "AM"
} else {
return time + "PM"
}
}
:white_check_mark:
const getUSTime = (time) => {
if(time <= 12) return time + "AM"
return time + "PM"
}
也可以使用三元表达式来写:
const getUSTime = (time) => {
return time + (time <= 12 ? "AM" : "PM")
}
(2)async/await
当使用链式的 Promise 时,代码的可读性就会变差。可以使用async/await来优化异步嵌套的代码。
const sharePost = () => {
getPost().then(post => {
sendTweet(post.url, `分享一篇文章: ${post.title}`)
.then(() => {
console.log("分享成功");
});
});
}
:white_check_mark:
const sharePost = async () => {
const post = await getPost();
await sendTweet(post.url, `分享一篇文章: ${post.title}`)
console.log("分享成功");
}
4. 干净的函数
(1)处理大量参数的函数
当函数的参数很多时,需要按照顺序传递参数就很麻烦,可以使用对象包装所有的参数,这样传递参数时就可以乱序传递,避免传参时出错。
function addUser(firstName, lastName, age, city, state, zipCode) {
// ...
}
:white_check_mark:
function addUser({ firstName, lastName, age, city, state, zipCode }) {
// ...
}
(2)单一责任原则
使用单一职责原则,可以轻松的命名函数,每个函数只做一件事。可以通过它的名称确切地知道该函数的作用,并且该函数不会是冗长的。
async function signupUser(email) {
const user = await User.create({ email });
await user.save();
const notifcation = await Notification.create({ email });
await notifcation.save();
const date = new Date()
Log.add(date, "已注册", email)
}
:white_check_mark:
const logSignup(email) => Log.add(new Date(), "已注册", email)
async function signupUser(email) {
createUser(email)
notifyUser(email)
logSignup(email)
}
async function createUser(email) {
const user = await User.create({ email });
await user.save();
}
async function notifyUser(email) {
const notifcation = await Notification.create({ email });
await notifcation.save();
}
(3)回调中首选箭头函数
在 JavaScript 中,map、filter等方法都需要一个匿名函数作为参数,在这些情况下,使用箭头函数是最方便和优雅的方式
[1, 2, 3].forEach(function (x) {
const y = x ** 2;
return x + y;
});
:white_check_mark:
[1, 2, 3].forEach((x) => {
const y = x ** 2;
return x + y;
});
Recommend
-
81
编写干净的代码并不是一件容易的事。它需要用不同的技巧和很多的实践。写出一手整洁的代码也是开发者们不断追求的目标。 编写干净代码的好处 项目更容易启动和延续 适合新团队人员加入项目组 更加容易理解 编写干净代码的要点 代码更加易读 为变量,函数和方法使用...
-
51
JavaScript起源于早期的网络。 从作为脚本语言开始,到现在它已经发展成为一种完全成熟的编程语言,并且支持服务器端执行。 现代Web应用程序严重依赖JavaScript,尤其是单页应用程序(SPA)。借助于React,AngularJS和Vue.js等新
-
19
夜深了。 我的同事把这周写的代码提交了。我们在开发一个图形编辑器画布,已经实现了形状调整功能,即通过拖拽形状边缘的手柄来调整形状(比如矩形和椭圆形)。 代码可以运行。 但重复代码有点多。每一种形状(比...
-
23
【51CTO.com快译】在金融行业,可...
-
7
使用 React 和 TypeScript something 编写干净代码的10个必知模式更新日期: 2022-03-09阅读量: 60标签:
-
1
《代码规范》如何写出干净的代码(一) ...
-
5
一个简单的步骤让你的 Python 代码更干净 作者:somenzz 2022-10-31 07:09:15 你可以将这两个文件拷贝到自己的项目根目录中,然后执行一次 pre-commit install,这样每次提交代码的时候,都是干净的代码,是不是很...
-
4
提升你的技能:编写干净高效的 JavaScript 的 7 个技巧 精选 原创 编写干净的代码对每个开发人员来说都是必不可少的,因为它使代...
-
7
“干净”的代码,贼差的性能 作者 | Casey Muratori 译者| 核子可乐 策划| 褚杏娟 如今很多机构里传授的所谓编程“最佳实践”,压根就是随时可能爆炸的性能灾难。 很多...
-
4
世界级编程大师Bob 大叔为“干净代码”辩护遭质疑:时代变了,别用Clean Code那套要求我们了!
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK