
英文 | https://javascript.plainenglish.io/as-a-front-end-engineer-10-javascript-tricks-and-tips-you-should-know-about-6f4df0082407
前言
過去,我寫了很多垃圾代碼,現在看起來很糟糕。
當我再次看到那些代碼片段時,我什至懷疑自己是否適合做程序員。
所以,這裡有 10 個我總結的JavaScript 技巧,可以幫助你避免編寫我曾經做過的那種垃圾代碼。
1. Promise 回調地獄
Promise 提供了一種優雅的方式來處理 JavaScript 中的異步操作。這也是避免「回調地獄」的解決方案之一。但是我並沒有真正理解它的含義,所以我寫了這個代碼片段。
我做了這些事情:
首先獲取用戶的基本信息。
按用戶信息獲取所有文章的簡要摘要。
通過文章簡要獲取文章詳細信息。
//❌getUserInfo() .then((userInfo) => { getArticles(userInfo) .then((articles) => { Promise.all(articles.map((article) => getArticleDetail(article))) .then((articleDetails) => { console.log(articleDetails) }) }) })我根本沒有在這裡利用 Promise,我們應該像下面的代碼片段一樣處理它:
// ✅getUserInfo() .then((getArticles) .then((articles) => { return Promise.all(articles.map((article) => getArticleDetail(article))) }) .then((articleDetails) => { console.log(articleDetails) })2.不處理錯誤信息
我經常只寫成功請求的代碼邏輯,而忽略請求失敗。
// ❌const getUserInfo = async () => { try { const userInfo = await fetch('/api/getUserInfo') } catch (err) { }}這是沒有經驗的,我們應該給出一個用戶友好的提示,而不是什麼都不做。
// ✅const getUserInfo = async () => { try { const userInfo = await fetch('/api/getUserInfo') } catch (err) { Toast(err.message) }}3. 給一個函數設置太多參數
當一個函數的參數太多時,它的可讀性就會降低,甚至,讓我們想知道如何正確傳遞參數。
例子
我們想要獲取用戶的一些基本信息,比如姓名、性別、年齡等。
// ❌const getUserInfo = (name, age, weight, gender, mobile , nationality, hobby, address) => { // ...}getUserInfo('fatfish', 100, 2000, ...)那太糟了,如果你的同事這樣寫代碼,你會揍他嗎?
事實上,當函數參數過多時,應該使用對象來傳遞需要的信息,這樣它的可讀性和可擴展性都會得到提高。
// ✅const getUserInfo = (options) => { const { name, gender, age, mobile, weight, nationality, hobby, address } = options // ...}getUserInfo({ name: 'fatfish', age: 100, weight: 2000 // ...})4.Magic number
朋友們,你們寫過這樣的代碼嗎?在很多地方使用數字進行邏輯判斷似乎很正常。是的,它讓我感到困惑 1、2、3 到底是什麼意思。
❌// component1.jsif (status === 1 || status === 2) { // ...} else if (status === 3) { // ...}// component2.jsif (status === 1 || status === 2) { // ...}我們最好將這些數字定義為常數。
// ✅// constants.jsexport const STATUS = { // It is an adult and has real-name authentication adultRealName: 1, // It is a minor and has real-name authentication minorRealName: 2, // Not real-name authentication notRealName: 3, // ...}// component1.jsimport { STATUS } from './constants.js'if ([ STATUS.adultRealName, STATUS.minorRealName ].includes(status)) { // ...} else if (status === STATUS.notRealName) { // ...}// component2.jsimport { STATUS } from './constants.js'// component2.jsif ([ STATUS.adultRealName, STATUS.minorRealName ].includes(status)) { // ...}5.使用.length判斷字符串的長度
大多數情況下,我們使用 .length 來判斷字符串的長度是安全的,但在表單輸入的情況下要小心。
當我們輸入 🍫 時,nameLen 的值為 2——這不是很奇怪嗎?
//❌<input type="text" id="name"><script> const $name = document.getElementById('name') $name.addEventListener('blur', () => { const name = $name.value const nameLen = name.length // input: fatfish => nameLen: 7 // input: 🍫 => nameLen: 2 console.log(`name: ${name}, nameLen: ${nameLen}`) }, false)</script>
是的,這是有原因的,你猜怎麼着?
// ✅<input type="text" id="name"><script> const $name = document.getElementById('name') $name.addEventListener('blur', () => { const name = $name.value const nameLen = name.length const spRegexp = /[\uD800-\uDBFF][\uDC00-\uDFFF]/g const nameRealLen = name.replace(spRegexp, '_').length // input: fatfish => nameLen: 7, nameRealLen: 7 // input: 🍫 => nameLen: 2, nameRealLen: 1 console.log(`name: ${name}, nameLen: ${nameLen}, nameRealLen: ${nameRealLen}`) }, false)</script>
6.永遠不要寫代碼注釋
我們經常向別人抱怨,「你為什麼不寫代碼注釋?」 但實際上,我自己也從來沒有寫過注釋!
//❌const fn = (dpr) => { if (dpr >= 2) { // ... } else { }}天哪,你知道'dpr'是什麼意思嗎? 我從沒想過它的意思是窗口設備PixelRatio。
// ✅// dpr: Please enter a value for window.devicePixelRatioconst fn = (dpr) => { if (dpr >= 2) { // ... } else { }}7. 無意義的代碼注釋
與其不寫代碼注釋,也不要寫無意義的代碼注釋,因為這會浪費你的時間。
你不妨解釋一下「a」的含義或使用有意義的變量名!
// ❌let a = 1 // Set the value of "a" to 18.隨機命名
過去,我曾經編寫過隨機命名變量的笨拙代碼片段。
朋友,請不要向我學習,你應該給變量一個適當且有意義的名稱。很多時候,我們的網站會不斷的調整功能,有新的和棄用的功能,但我總是擔心我以後會用到,所以我只是評論它們,而不是刪除它們。其實,這種擔心是完全沒有必要的,因為以後用的可能性很小。 就算以後會用到,也可以通過『git』來追溯。
我在一個組件中編寫了超過一千行代碼。 這太糟糕了,我們應該將組件的功能進一步拆分為更小的組件。
這些都是我工作的一些經驗總結,希望這篇文章內容對你有所幫助,最後,謝謝您的閱讀,同時,也期待您關注我,點讚我,以及閱讀更多其他文章。學習更多技能
請點擊下方公眾號


