当前位置: 首页 > 科技观察

让你的JavaScript代码库更干净的五种方法

时间:2023-03-21 12:11:42 科技观察

1.使用默认参数而不是短路或有条件的默认参数通常比短路更干净。functionSomeMethod(paramThatCanBeUndefined){constlocalValue=paramThatCanBeUndefined||"DefaultValue";console.log(localValue)//...}SomeMethod()//DefaultValueSomeMethod("SomeValue")//SomeValue尝试下面的方法:functionSomeMethod(console.log(paramThatCanBeUndefined)//...}SomeMethod()//DefaultValueSomeMethod("SomeValue")//SomeValue声明:''、""、false、null、0、NaN等Falsy值默认不会被替换values:functionSomeMethod(paramThatCanBeUndefined="DefaultValue"){console.log(paramThatCanBeUndefined)//...}SomeMethod(null)//willnotDefaultValue,willnullInsteadSomeMethod("SomeValue")//SomeValue2,处理多个条件constconditions=["Condition2","ConditionString2"];someFunction(str){if(str.includes("someValue1")||str.includes("someValue2")){returntrue}else{returnfalse}}更简洁的方法是:someFunction(str){constconditions=["someValue1","someValue2"];returnconditions.some(condition=>str.includes(condition));}3.将开关(即对象文字)开关版本替换为动态键值对(或将开关替换为if/else):constUserRole={ADMIN:"Admin",GENERAL_USER:"普通用户",SUPER_ADMIN:"超级管理员",};functiongetRoute(userRole="defaultrole"){switch(userRole){caseUserRole.ADMIN:return"/admin"caseUserRole.GENERAL_USER:return"/GENERAL_USER"caseUserRole.SUPER_ADMIN:return"/superadmin"default:return"/"}}console.log(getRoute(UserRole.ADMIN))//return"/admin"console.log(getRoute("Anything"))//returnDefaultpathconsole.log(getRoute())//returnDefaultpathconsole.log(getRoute(null))//returnDefaultpath//Morecasesifnewarrive//Youcanthinkifelseinsteadofswitch动态键值对版本:constUserRole={ADMIN:"Admin",GENERAL_USER:"GeneralUser",SUPER_ADMIN:"SuperAdmin",};functiongetRoute(userRole="defaultrole"){constappRoute={[UserRole.ADMIN]:"/admin",[UserRole.GENERAL_USER]:"/user",[UserRole.SUPER_ADMIN]:"/superadmin"};returnappRoute[userRole]||"Defaultpath";}console.log(getRoute(UserRole.ADMIN))//return"/admin"console.log(getRoute("Anything"))//returnDefaultpathconsole.log(getRoute())//returnDefaultpathconsole.log(getRoute(null))//returnDefaultpath//Nomoreswitch/if-elsehere.//EasytoFurtherexpansion4.避免函数参数过多functionmyFunction(employeeName,jobTitle,yrExp,majorExp){return`${employeeName}isworkingas${jobTitle}with${yrExp}yearsofexperiencein${majorExp}`}//outputbelikeJohnisworkingasProjectManagerwith12yearofexperienceinProjectManagerwith12yearofexperienceinProjectManagement//log"myconcallitvia("John"ProjectManager",12"ProjectManagement"))//*****PROBLEMSARE*****//违反'cleancode'原则//Parametersequencingisimportant//UnusedParamswarningifnotused//Testingneedtoconsideralotofedgecases.这里有一个更干净的方法:functionmyFunction({employeeName,jobTitle,yrExp,majorExp}){return`${employeeName}isworkingas${jobTitle}with${yrExp}yearsofexperiencein${majorExp}`}//outputbelikeJohnisworkingasProjectManagerwith12yearofexperienceinProjectManagement//youcancallitviaconstmockTechPeople={employeeName:"John",jobTitle:"ProjectManager",yrExp:12,majorExp:"ProjectManagement"}console.log(myFunction(mockTechPeople))//ES2015/ES6destructuringsyntaxisinaction//mapyourdesiredvaluetovariableyouneed.5、使用Object.assign设置默认对象这看起来很繁琐:constsomeObject={title:null,subTitle",buttonColor:null,disabled:true};functioncreateOption(someObject){someObject.title=someObject.title||"DefaultTitle";someObject.subTitle=someObject.subTitle||"DefaultSubtitle";someObject.buttonColor=someObject.buttonColor||"blue";someObject.disabled=someObject.disabled!==undefined?someObject.disabled:true;returnssomeObject}console.log(createOption(someObject));//Outputbelike//{title:'DefaultTitle',subTitle:'Subtitle',buttonColor:'blue',disabled:true}这种方法看起来更好:constsomeObject={title:null,subTitle:"Subtitle",buttonColor:null,disabled:true};functioncreteOption(someObject){constnewObject=Object.assign({title:"DefaultTitle",subTitle:"DefaultSubtitle",buttonColor:"blue",disabled:true},someObject)returnnewObject}console.log(creteOption(someObject));