【免费赠书】6 种在 JavaScript 中清理代码的方法
web前端开发
共 3545字,需浏览 8分钟
·
2021-12-01 10:33
// 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')
)
// 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')
)
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)
}
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'
}
// The key is already the perfect variable name, why not use it?
const userFirstName = user.firstName
// Much cleaner!
const { firstName } = user
总结
以上就是我今天与您分享的内容,希望对您有所帮助,如果您有什么问题,请在留言区给我留言交流学习。
最后,感谢您的阅读,祝编程愉快!
另外,今天我还给大家带了两本图书《Vue.js框架与Web前端开发从入门到精通》和《 Node.js入门指南》,免费赠送给大家,希望大家会喜欢,以下是赠书的规则:
1、必须是关注了我们【web前端开发】公众号的读者。
2、要在留言区里给我们留言,说说你为啥想要这本书,或者是你的编程趣事。
3、留言点赞数最高的前8位读者朋友们(点赞数相同按系统顺序排序),就可以任意选择其中一本书,免费领回家。
这3点必须同时满足哦~
活动截止时间:2021年11月30日晚上9点,中奖者名单,将在2021年12月1日的头条文章推送中的PS里进行公布。请大家自行关注。
所赠送图书均包邮到家。
赠送图书的图片如下:
《Vue.js框架与Web前端开发从入门到精通》
《 Node.js入门指南》
学习更多技能
请点击下方公众号
评论