深圳幻海软件技术有限公司 欢迎您!

十个必须知道的 JavaScript 技巧,让你成为更好的程序员

2023-02-28

前言过去,我写了很多垃圾代码,现在,看起来很糟糕。当我再次看到那些代码片段时,我甚至怀疑自己是否适合做一名程序员,但是,不管怎么样,已经走在编程开发的路上了,所以不会不懂只能多学习了。现在,我就把自己踩过的坑总结一下分享给你,希望对你有所帮助。1.Promise回调地狱Promises提供了一种优雅

前言

过去,我写了很多垃圾代码,现在,看起来很糟糕。

当我再次看到那些代码片段时,我甚至怀疑自己是否适合做一名程序员,但是,不管怎么样,已经走在编程开发的路上了,所以不会不懂只能多学习了。

现在,我就把自己踩过的坑总结一下分享给你,希望对你有所帮助。

1. Promise回调地狱

Promises 提供了一种优雅的方式来处理 JavaScript 中的异步操作。这也是避免“回调地狱”的解决方案之一。但是我并没有真正理解它的意思,所以我写了这段代码。

我做了这些事情:

    QQ6Aca">
  • 先获取用户的基本信息。
  • 按用户信息获取所有文章的简要摘要。
  • 通过文章简单获取文章详情。
// ❌
getUserInfo()
  .then((userInfo) => {
    getArticles(userInfo)
      .then((articles) => {
        Promise.all(articles.map((article) => getArticleDetail(article)))
          .then((articleDetails) => {
            console.log(articleDetails)
          })
      })
  })
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.

我在这里根本没有利用 Promise,我们应该像下面的代码片段一样处理它:

// ✅
getUserInfo()
  .then((getArticles)
  .then((articles) => {
    return Promise.all(articles.map((article) => getArticleDetail(article)))
  })
  .then((articleDetails) => {
    console.log(articleDetails)
  })
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.

2.不处理错误信息

我经常只写请求成功的代码逻辑,而忽略请求失败的代码逻辑。

// ❌
const getUserInfo = async () => {
  try {
    const userInfo = await fetch('/api/getUserInfo')
  } catch (err) {


  }
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.

这是没有经验的,我们应该给出一个用户友好的提示,而不是什么都不做。

// ✅
const getUserInfo = async () => {
  try {
    const userInfo = await fetch('/api/getUserInfo')
  } catch (err) {
    Toast(err.message)
  }
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.

3. 为函数设置太多参数

当一个函数的参数过多时,它的可读性就会变差,甚至不知道如何正确传递参数。

例子

我们想获取用户的一些基本信息,比如姓名、性别、年龄等。

// ❌
const getUserInfo = (name, age, weight, gender, mobile , nationality, hobby, address) => {
  // ...
}
getUserInfo('fatfish', 100, 2000, ...)
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.

以上这样的代码,那真是太糟了,如果你的同事这样写代码,你会揍他吗?

事实上,当函数参数过多时,应该使用对象来传递需要的信息,这样会提高其可读性和扩展性。

// ✅
const getUserInfo = (options) => {
  const { name, gender, age, mobile, weight, nationality, hobby, address } = options
  // ...
}
getUserInfo({
  name: 'fatfish',
  age: 100,
  weight: 2000
  // ...
})
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.

4.神奇的数字

小伙伴们,你们写过这样的代码吗?很多地方用数字来做逻辑判断似乎很正常。是的,这让我很困惑 1、2、3 到底是什么意思。


// component1.js
if (status === 1 || status === 2) {
  // ...
} else if (status === 3) {
  // ...
}
// component2.js
if (status === 1 || status === 2) {
  // ...
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.

我们最好将这些数字定义为常量。

// ✅
// 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.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.

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>
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.

是的,这是有原因的,你猜怎么着?

// ✅
<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.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.

6. 永远不要写代码注释

我们经常向别人抱怨,“你为什么不写代码注释?” 但实际上,我们自己也从来不写它!

// ❌
const fn = (dpr) => {
  if (dpr >= 2) {
    // ...
  } else {
  }
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.

我的天,你知道‘dpr’是什么意思吗?没想到是指window devicePixelRatio。

// ✅
// dpr: Please enter a value for window.devicePixelRatio
const fn = (dpr) => {
  if (dpr >= 2) {
    // ...
  } else {
  }
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.

7.无意义的代码注释

与其不写代码注释,也不要写无意义的代码注释,因为它浪费了你的时间。

你不妨解释一下“a”的含义或使用有意义的变量名称!

// ❌
let a = 1 // Set the value of "a" to 1
  • 1.
  • 2.

8. 随机命名

过去,我常常编写随机命名变量的笨拙代码片段。

// ❌
const mw = 375
  • 1.
  • 2.

因此,亲爱的朋友们,请你们不要学我,你应该给变量一个适当且有意义的名称。


const maxWidth = 375
  • 1.
  • 2.

9. 删除不要弃用的代码

很多时候,我们的网站会不断调整功能,有新功能也有过时的功能,但我总是担心以后会用到,所以我们总是注释掉,并没有删除。

其实这种担心是完全没有必要的,因为以后用到的可能性很小。即使以后要用到,也可以通过‘git’来追溯。

10. 上千行组件代码

我已经在一个组件中编写了一千多行代码。这太糟糕了,我们应该将组件的功能进一步拆分成更小的组件。

最后

感谢你的阅读,以上就是我今天想要跟你分享的内容,如果你觉得我的内容对你有用的话,请点赞我,关注我,同时,也期待你的关注,这样,你将会阅读到更多编程技术相关的文章。