日本综合一区二区|亚洲中文天堂综合|日韩欧美自拍一区|男女精品天堂一区|欧美自拍第6页亚洲成人精品一区|亚洲黄色天堂一区二区成人|超碰91偷拍第一页|日韩av夜夜嗨中文字幕|久久蜜综合视频官网|精美人妻一区二区三区

RELATEED CONSULTING
相關(guān)咨詢
選擇下列產(chǎn)品馬上在線溝通
服務(wù)時間:8:30-17:00
你可能遇到了下面的問題
關(guān)閉右側(cè)工具欄

新聞中心

這里有您想知道的互聯(lián)網(wǎng)營銷解決方案
如何編寫干凈的JavaScript代碼?

1. 更好的命名

在 JavaScript 中,良好命名的關(guān)鍵不在于最短的變量名,而在于最具描述性的變量名。

成都創(chuàng)新互聯(lián)公司專注于廣陽企業(yè)網(wǎng)站建設(shè),響應(yīng)式網(wǎng)站,商城網(wǎng)站制作。廣陽網(wǎng)站建設(shè)公司,為廣陽等地區(qū)提供建站服務(wù)。全流程按需定制制作,專業(yè)設(shè)計,全程項目跟蹤,成都創(chuàng)新互聯(lián)公司專業(yè)和態(tài)度為您提供的服務(wù)

(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; // 布爾值應(yīng)該有一個類似于is、has或was的前綴
const expiredDate = new Date()
let expiredElementsAmount = 0
let allExpiredElemnts = []

2. 保持簡潔

(1)避免重復(fù)

為了更好地實現(xiàn)簡潔的代碼,應(yīng)該遵循DRY(Don't Repeat Yourself)原則。減少代碼的重復(fù)。

  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

當(dāng)使用鏈?zhǔn)降?Promise 時,代碼的可讀性就會變差。可以使用async/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ù)

當(dāng)函數(shù)的參數(shù)很多時,需要按照順序傳遞參數(shù)就很麻煩,可以使用對象包裝所有的參數(shù),這樣傳遞參數(shù)時就可以亂序傳遞,避免傳參時出錯。

function addUser(firstName, lastName, age, city, state, zipCode) {
// ...
}

function addUser({ firstName, lastName, age, city, state, zipCode }) {
// ...
}

(2)單一責(zé)任原則

使用單一職責(zé)原則,可以輕松的命名函數(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;
});


網(wǎng)頁標(biāo)題:如何編寫干凈的JavaScript代碼?
URL地址:http://www.dlmjj.cn/article/cdihhch.html