1、删除不必要的 return 语句:
检查函数内部是否需要存在。可以简化为一行代码吗?如果是这样,JavaScript 允许使用隐式返回来简化代码。
从下面检查代码。在那里,我删除了额外的变量声明 usersFound,让我可以选择删除未使用的 return 语句。
// This function receives as arguments an array of objects,
// [{ firstName: ‘Test’ }, { firstName: ‘Ignacio’ }, …]
// This function returns all the users with name ‘Test’
const findTestNameUsers = (users) => {
const usersFound = users.filter((user) => {
return user.firstName === ‘Test’
})
return usersFound
}
// This function has the same behaviour as the one above.
// This function uses implicit return statements
const findTestNameUsers = (users) => (
users.filter(user => user.firstName === ‘Test’)
)
2 、变量名称应具有描述性:
一个好的变量名有助于提高代码的可读性。避免使用字母甚至 for 循环。还要记住使用驼峰命名法,它是 JavaScript 的标准命名约定。
让我继续使用上面的例子。
// This function receives as arguments an array of objects,
// [{ firstName: ‘Test’ }, { firstName: ‘Ignacio’ }, …]
// This function returns all the users with name ‘Test’
const newFunction = (a) => (
a.filter(u => u.firstName === ‘Test’)
)
// You can see, how by giving better naming to the function it
// is easier to identify what they do.
const findTestNameUsers = (users) => (
users.filter(user => user.firstName === ‘Test’)
)
3 、仅在返回原始值时使用三元条件:
避免在三元条件中添加复杂的逻辑。他们有时已经令人困惑。尝试在三元条件下返回一个原始值,否则不要害怕使用 if 和 else 条件。
const greeting = true
const welcomeGreeting = ‘Welcome to the condition’
const notWelcome = ‘Not Welcome to the condition’
const notGreeting = ‘No Greeting for you’
// Pretty confusing the line below…
const value = greeting ? welcomeGreeting ? welcomeGreeting : notWelcome : noGreeting
console.log(value) // will console.log Welcome to the condition.
// Let me change that to make it easier to read,
// we will add a couple more lines but it will make your life
// easier.
const greeting = true
const welcomeGreeting = ‘Welcome to the condition’
const notWelcome = ‘Not Welcome to the condition’
const notGreeting = ‘No Greeting for you’
if(greeting) {
console.log(welcomeGreeting ? welcomeGreeting : notWelcome)
} else {
console.log(noGreeting)
}
4 、在检查中使用正值:
在将否定检查转换为肯定检查时,我们的大脑必须进行额外的操作。尝试通过将其转换为正面检查来删除该额外步骤。
const argument = null
// For this check, you will have to make an extra operation,
// ! => not, therefore, if there is NO argument,
// then run the following block.
if (!argument) {
return ‘The argument is empty’
} else {
return ‘The argument is not empty’
}
// Let’s convert the previous block to a positive check
const argument = null
if (argument) {
return ‘The argument is present’
} else {
return ‘The argument is not present’
}
5 、在访问函数参数或对象中的值时使用解构:
JavaScript 中的解构是一个很好的工具。它可以帮助您避免在已经提供给您时创建新的变量名称。
// The key is already the perfect variable name, why not use it?
const userFirstName = user.firstName
// Much cleaner!
const { firstName } = user
6 、使用现有的格式化工具来帮助您格式化代码
已经有一些工具可以帮助您格式化代码以满足该语言的最佳实践。
我只会向已经有 JavaScript 经验的开发人员推荐这个工具。我相信学习 JavaScript 的最佳实践对新开发人员是有好处的。
我建议你看看Prettier,地址:https://prettier.io/
今天爱创课堂小编的分享就到这里了,有想学习前端,了解前端更多知识的同学,欢迎大家私信小编领取前端学习资料,也可以关注,点赞加分享,多多支持小编!!!