3

十个前端开发者务必知道的JavaScript 技巧

 1 year ago
source link: https://www.51cto.com/article/720973.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

十个前端开发者务必知道的JavaScript 技巧

作者:佚名 2022-10-20 15:12:43
这里有 10 个我总结的JavaScript 技巧,可以帮助你避免编写我曾经做过的那种垃圾代码。

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

当我再次看到那些代码片段时,我什至怀疑自己是否适合做程序员。

所以,这里有 10 个我总结的JavaScript 技巧,可以帮助你避免编写我曾经做过的那种垃圾代码。

1. Promise 回调地狱

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

我做了这些事情:

  • 首先获取用户的基本信息。
  • 按用户信息获取所有文章的简要摘要。
  • 通过文章简要获取文章详细信息。
// ❌getUserInfo()(userInfo) =>    getArticles(userInfo)(articles) =>        Promise.all(articles.map((article) =>(articleDetails) =>            console.log(articleDetails)          })      })  })

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

// ✅getUserInfo()  .then((getArticles)(articles) =>    return Promise.all(articles.map((article) =>  })(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 1

8.随机命名

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

// ❌const mw = 375

朋友,请不要向我学习,你应该给变量一个适当且有意义的名称。

✅const maxWidth = 375

9.不要删除不推荐使用的代码

很多时候,我们的网站会不断的调整功能,有新的和弃用的功能,但我总是担心我以后会用到,所以我只是评论它们,而不是删除它们。

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

图片

10. 超过一千行的组件代码

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

图片

这些都是我工作的一些经验总结,希望这篇文章内容对你有所帮助。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK