如何編寫干凈的JavaScript代碼?
今天來分享幾個編寫干凈的JavaScript代碼的技巧!
1. 更好的命名
在 JavaScript 中,良好命名的關鍵不在于最短的變量名,而在于最具描述性的變量名。
(1)減少幻數(shù)
將代碼中的一些數(shù)字定義為一個常量,以使它更有意義,也便于后期的維護。
?
for (i=0; i < 8765; i++)
?
const HOURS_IN_A_YEAR = 8765
for (i=0; i < HOURS_IN_A_YEAR; i++)
(2)語義化命名
盡可能語義化變量和函數(shù)的名稱。
?
onst expired = true;
const e = true;
?
const hasExpired = true; // 布爾值應該有一個類似于is、has或was的前綴
const expiredDate = new Date()
let expiredElementsAmount = 0
let allExpiredElemnts =
2. 保持簡潔
(1)避免重復
為了更好地實現(xiàn)簡潔的代碼,應該遵循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();
?
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
?
const stepsToHundred = (number, steps) =>
number < 100 ? stepsToHundred(number * 2, steps + 1) steps
(3)字符串連接
ES6中新增了模板字符串功能使我們可以在拼接字符串時代碼更短、更簡潔。
?
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"
?
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 時,代碼的可讀性就會變差??梢允褂胊sync/await來優(yōu)化異步嵌套的代碼。
?
const sharePost = () =>
getPost().then(post =>
sendTweet(post.url, `分享一篇文章 $ post.title `)
.then(() =>
console.log("分享成功");
);
);
?
const sharePost = async () =>
const post = await getPost();
await sendTweet(post.url, `分享一篇文章 $ post.title `)
console.log("分享成功");
4. 干凈的函數(shù)
(1)處理大量參數(shù)的函數(shù)
當函數(shù)的參數(shù)很多時,需要按照順序傳遞參數(shù)就很麻煩,可以使用對象包裝所有的參數(shù),這樣傳遞參數(shù)時就可以亂序傳遞,避免傳參時出錯。
?
function addUser(firstName, lastName, age, city, state, zipCode)
// ...
?
function addUser(firstName lastName age city state zipCode )
// ...
(2)單一責任原則
使用單一職責原則,可以輕松的命名函數(shù),每個函數(shù)只做一件事??梢酝ㄟ^它的名稱確切地知道該函數(shù)的作用,并且該函數(shù)不會是冗長的。
?
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)
?
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)回調(diào)中首選箭頭函數(shù)
在 JavaScript 中,map、filter等方法都需要一個匿名函數(shù)作為參數(shù),在這些情況下,使用箭頭函數(shù)是最方便和優(yōu)雅的方式
?
1 2 3 .forEach(function (x)
const y = x ** 2;
return x + y;
);
?
[1, 2, 3].forEach((x) => {
const y = x ** 2;
return x + y;
});