5种使JavaScript代码库更干净的方法
WEB前端开发社区 3天前
JavaScript无处不在,从PC端到移动设备端,甚至是后端,都在使用JavaScript。
在本文中,我将尝试一些可用来使代码看起来更简洁的实践方案。
1、使用默认参数代替短路或条件
默认参数通常比短路更干净。
function SomeMethod(paramThatCanBeUndefined) {const localValue = paramThatCanBeUndefined || "Default Value";console.log(localValue)// ...}SomeMethod() // Default ValueSomeMethod("SomeValue") // SomeValue
function SomeMethod( console.log(paramThatCanBeUndefined) // ...}SomeMethod() // Default ValueSomeMethod("SomeValue") // SomeValue
function SomeMethod(paramThatCanBeUndefined = "Default Value") { console.log(paramThatCanBeUndefined) // ...}SomeMethod(null) // will not Default Value, will null InsteadSomeMethod("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、用动态键值对替换开关(即对象文字)
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 pathconsole.log(getRoute()) // return Default pathconsole.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 pathconsole.log(getRoute()) // return Default pathconsole.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 viaconsole.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 viaconst 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));
赞 (0)