天天看點

前端開發者務必知道的JavaScript技巧

前端開發者務必知道的JavaScript技巧,這裡有 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)
  }
}      
  1. 給一個函數設定太多參數

當一個函數的參數太多時,它的可讀性就會降低,甚至,讓我們想知道如何正确傳遞參數。

例子

我們想要擷取使用者的一些基本資訊,比如姓名、性别、年齡等。

// ❌
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
  // ...
})      
  1. Magic number

朋友們,你們寫過這樣的代碼嗎?在很多地方使用數字進行邏輯判斷似乎很正常。是的,它讓我感到困惑 1、2、3 到底是什麼意思。

❌
// component1.js
if (status === 1 || status === 2) {
  // ...
} else if (status === 3) {
  // ...
}
// component2.js
if (status === 1 || status === 2) {
  // ...
}      

我們最好将這些數字定義為常數。

// ✅
// constants.js
export 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.js
import { STATUS } from './constants.js'
if ([ STATUS.adultRealName, STATUS.minorRealName ].includes(status)) {
  // ...
} else if (status === STATUS.notRealName) {
  // ...
}
// component2.js
import { STATUS } from './constants.js'
// component2.js
if ([ STATUS.adultRealName, STATUS.minorRealName ].includes(status)) {
  // ...
}      
  1. 使用.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>      
前端開發者務必知道的JavaScript技巧

是的,這是有原因的,你猜怎麼着?

// ✅
<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>
      
  1. 永遠不要寫代碼注釋

我們經常向别人抱怨,“你為什麼不寫代碼注釋?” 但實際上,我自己也從來沒有寫過注釋!

// ❌
const fn = (dpr) => {
  if (dpr >= 2) {
    // ...
  } else {
  }
}      

天哪,你知道'dpr'是什麼意思嗎?我從沒想過它的意思是視窗裝置PixelRatio。

// ✅
// dpr: Please enter a value for window.devicePixelRatio
const fn = (dpr) => {
  if (dpr >= 2) {
    // ...
  } else {
  }
}      
  1. 無意義的代碼注釋

與其不寫代碼注釋,也不要寫無意義的代碼注釋,因為這會浪費你的時間。

你不妨解釋一下“a”的含義或使用有意義的變量名!

// ❌
let a = 1 // Set the value of "a" to 1      
  1. 随機命名

過去,我曾經編寫過随機命名變量的笨拙代碼片段。

// ❌
const mw = 375      

朋友,請不要向我學習,你應該給變量一個适當且有意義的名稱。

✅
const maxWidth = 375      
  1. 不要删除不推薦使用的代碼

很多時候,我們的網站會不斷的調整功能,有新的和棄用的功能,但我總是擔心我以後會用到,是以我隻是評論它們,而不是删除它們。其實,這種擔心是完全沒有必要的,因為以後用的可能性很小。就算以後會用到,也可以通過‘git’來追溯。

前端開發者務必知道的JavaScript技巧
  1. 超過一千行的元件代碼

繼續閱讀