5 种使 JavaScript 代码更干净的方法
前端技术江湖
共 4561字,需浏览 10分钟
· 2021-12-30
点击上方关注 前端技术江湖,一起学习,天天进步
JavaScript无处不在,从PC端到移动设备端,甚至是后端,都在使用JavaScript。
在本文中,我将尝试一些可用来使代码看起来更简洁的实践方案。
1、使用默认参数代替短路或条件
默认参数通常比短路更干净。
function SomeMethod(paramThatCanBeUndefined) {
const localValue = paramThatCanBeUndefined || "Default Value";
console.log(localValue)
// ...
}
SomeMethod() // Default Value
SomeMethod("SomeValue") // SomeValue
尝试以下方法:
function SomeMethod(
console.log(paramThatCanBeUndefined)
// ...
}
SomeMethod() // Default Value
SomeMethod("SomeValue") // SomeValue
声明:Falsy值,如'',"",false,null,0,和NaN将不会被默认值替代:
function SomeMethod(paramThatCanBeUndefined = "Default Value") {
console.log(paramThatCanBeUndefined)
// ...
}
SomeMethod(null) // will not Default Value, will null Instead
SomeMethod("SomeValue") // SomeValue
2、处理多个条件
const conditions = ["Condition 2","Condition String2"];
someFunction(str){
if(str.includes("someValue1") || str.includes("someValue2")){
return true
}else{
return false
}
}
一种更干净的方法是:
someFunction(str){
const conditions = ["someValue1","someValue2"];
return conditions.some(condition=>str.includes(condition));
}
3、用动态键值对替换开关(即对象文字)
开关版本(或将开关替换为if / else):
const UserRole = {
ADMIN: "Admin",
GENERAL_USER: "GeneralUser",
SUPER_ADMIN: "SuperAdmin",
};
function getRoute(userRole = "default role"){
switch(userRole){
case UserRole.ADMIN:
return "/admin"
case UserRole.GENERAL_USER:
return "/GENERAL_USER"
case UserRole.SUPER_ADMIN:
return "/superadmin"
default:
return "/"
}
}
console.log(getRoute(UserRole.ADMIN)) // return "/admin"
console.log(getRoute("Anything")) // return Default path
console.log(getRoute()) // return Default path
console.log(getRoute(null)) // return Default path
// More cases if new arrive
// You can think if else instead of switch
动态键值对版本:
const UserRole = {
ADMIN: "Admin",
GENERAL_USER: "GeneralUser",
SUPER_ADMIN: "SuperAdmin",
};
function getRoute(userRole = "default role"){
const appRoute = {
[UserRole.ADMIN]: "/admin",
[UserRole.GENERAL_USER]: "/user",
[UserRole.SUPER_ADMIN]: "/superadmin"
};
return appRoute[userRole] || "Default path";
}
console.log(getRoute(UserRole.ADMIN)) // return "/admin"
console.log(getRoute("Anything")) // return Default path
console.log(getRoute()) // return Default path
console.log(getRoute(null)) // return Default path
// No more switch/if-else here.
// Easy to Further expansion
4、避免过多的函数参数
function myFunction(employeeName,jobTitle,yrExp,majorExp){
return `${employeeName} is working as ${jobTitle} with ${yrExp} years of experience in ${majorExp}`
}
//output be like John is working as Project Manager with 12 year of experience in Project Management
// you can call it via
console.log(myFunction("John","Project Manager",12,"Project Management"))
// ***** PROBLEMS ARE *****
// Violation of 'clean code' principle
// Parameter sequencing is important
// Unused Params warning if not used
// Testing need to consider a lot of edge cases.
这是一种更清洁的方法:
function myFunction({employeeName,jobTitle,yrExp,majorExp}){
return `${employeeName} is working as ${jobTitle} with ${yrExp} years of experience in ${majorExp}`
}
//output be like John is working as Project Manager with 12 year of experience in Project Management
// you can call it via
const mockTechPeople = {
employeeName:"John",
jobTitle:"Project Manager",
yrExp:12,
majorExp:"Project Management"
}
console.log(myFunction(mockTechPeople))
// ES2015/ES6 destructuring syntax is in action
// map your desired value to variable you need.
5、使用Object.assign设置默认对象
这看起来很繁琐:
const someObject = {
title: null,
subTitle: "Subtitle",
buttonColor: null,
disabled: true
};
function createOption(someObject) {
someObject.title = someObject.title || "Default Title";
someObject.subTitle = someObject.subTitle || "Default Subtitle";
someObject.buttonColor = someObject.buttonColor || "blue";
someObject.disabled = someObject.disabled !== undefined ? someObject.disabled : true;
return someObject
}
console.log(createOption(someObject));
// Output be like
// {title: 'Default Title', subTitle: 'Subtitle', buttonColor: 'blue', disabled: true}
这种方法看起来更好:
const someObject = {
title: null,
subTitle: "Subtitle",
buttonColor: null,
disabled: true
};
function creteOption(someObject) {
const newObject = Object.assign({
title: "Default Title",
subTitle: "Default Subtitle",
buttonColor: "blue",
disabled: true
},someObject)
return newObject
}
console.log(creteOption(someObject));
最后,谢谢你的阅读,祝编程愉快!
The End
欢迎自荐投稿到《前端技术江湖》,如果你觉得这篇内容对你挺有启发,记得点个 「在看」哦
点个『在看』支持下
评论
真高!比亚迪员工爆料比亚迪在越南的薪资水平:基本工资480万,全勤奖35万,交通补助20万,餐补110万,每周6天,每天10小时
上一篇:某大公司为逼迫员工离职,竟然把他的工位安排到厕所旁,没想到他直接开始记录领导的如厕时间,还发到公司大群...对此,你怎么看?--完--PS:欢迎在留言区留下你的观点,一起讨论提高。如果今天的文章让你有新的启发,欢迎转发分享给更多人。全文完,感谢你的耐心阅读。如果你还想看到我的文章,请一定给本
开发者全社区
0
太敢穿了!透视纱裙!性感火辣的身材
绝了呀今天的厂花:吴宣仪1995年1月26日,吴宣仪出生于海南省海口市,中国内地流行乐女歌手、影视演员。2016年2月,吴宣仪随宇宙少女发行首张迷你专辑正式出道。2018年4月,她参加《创造101》综艺选秀,获得第二名,成功加入火箭少女101组合。吴宣仪的颜值一直备受称赞,她的五官立体精致,皮肤白皙
逆锋起笔
0
某大公司为逼迫员工离职,竟然把他的工位安排到厕所旁,没想到他直接开始记录领导的如厕时间,还发到公司大群...
上一篇:字节的跳动职级与薪资(2024年)我们与公司间的合作,宛如两艘船只在茫茫大海上相互依靠,共同抵御风浪,携手驶向成功的彼岸。然而,当航向开始产生分歧,或是波涛汹涌的风浪改变了我们的初衷,我们或许应当冷静地选择和平分手,而非在风雨中硬撑。最近,一位网友的遭遇引起了广大职场人的关注和热议。这位网友
开发者全社区
0
金融研究 | 使用Python测量关键审计事项的「信息含量」
Tips: 公众号推送后内容只能更改一次,且只能改20字符。如果内容出问题,或者想更新内容, 只能重复推送。为了更好的阅读体验,建议阅读本文博客版, 链接地址https://textdata.cn/blog/2023-01-13-information-content-of-critical-aud
大邓和他的Python
0
我看阿里的年终奖总算发了!
到4月底了,这两天看朋友圈,发现阿里的年终奖终于发了,问了问老同学,也从网上检索了不少信息,基本搞清楚了阿里今年的年终奖情况。近来来阿里一些集团对绩效等级做了较大的调整,以前的旧绩效系统中,绩效分为3.25、3.5、3.75、4和5五个等级,其中4和5是较高绩效等级,较少见。而且之前3.5绩效内部划
公子龙
0
CVPR 2024|大视觉模型的开山之作!无需任何语言数据即可打造大视觉模型
↑ 点击蓝字 关注极市平台作者丨科技猛兽编辑丨极市平台极市导读 本文提出一种序列建模 (sequential modeling) 的方法,不使用任何语言数据,训练大视觉模型。>>加入极市CV技术交流群,走在计算机视觉的最前沿本文目录1 序列建模打造大视觉模型(来自 U
极市平台
1
金融研究(更新) | 使用Python构建关键审计事项的「信息含量」
Tips: 公众号推送后内容只能更改一次,且只能改20字符。如果内容出问题,或者想更新内容, 只能重复推送。为了更好的阅读体验,建议阅读本文博客版, 链接地址https://textdata.cn/blog/2023-01-13-information-content-of-critical-aud
大邓和他的Python
0
字节的跳动职级与薪资(2024年)
上一篇:阿里公布年终奖,P7, 3.5+,22W年终奖,还有35W长期现金激励,真香字节跳动自2012年3月成立以来,已经迅速成长为一个全球性的科技公司。其产品和服务已经遍布全球150多个国家与地区,并且支持超过75种不同的语言。在字节跳动的官方网站上,列出了一系列引人注目的产品和服务,包括但不限于
开发者全社区
0