当前位置: 首页 > Web前端 > vue.js

使用这些技巧来优化IF语句

时间:2023-03-31 23:06:56 vue.js

作者:DamianCiplat具有向上和积极态度的人。本文已收录到GitHubhttps://github.com/qq44924588...,文章已分类,也整理了很多我的文档和教程资料。最近开源了一个Vue组件,但是还不够完善。欢迎大家一起完善,也希望大家能给个star支持一下。谢谢。github地址:https://github.com/qq44924588...双12阿里服务器27元,一般点这里购买,可以找我返现30,相当于27元购买,仅限新用户,可以用家人手机号购买!最近在重构代码的时候,发现之前的代码使用了太多的if语句,达到了前所未有的程度。这就是为什么我认为分享这些可以帮助我们避免过度使用if语句的简单技巧非常重要。接下来介绍6种替换if使用的方法。这并不是坚决不使用if偏执,而是换一种方式来思考我们的编码思路。1.三元运算符案例1IF重构后的代码:functionsaveCustomer(customer){if(isCustomerValid(customer)){database.save(customer)}else{alert('customerisinvalid')}}代码:functionsaveCustomer(客户){返回isCustomerValid(客户)?database.save(customer):alert('customerisinvalid')}使用ES6constsaveCustomer=customer=>isCustomerValid(customer)?database.save(customer):alert('customerisinvalid')带有IF的案例2代码:functioncustomerValidation(customer){if(!customer.email){returnerror('emailisrequire')}elseif(!customer.login){returnerror('loginisrequired')}elseif(!customer.name){returnerror('nameisrequired')}else{returncustomer}}重构代码:constcustomerValidation=customer=>!customer。电子邮件?错误(“需要电子邮件”):!customer.login?错误('需要登录'):!客户名称?error('nameisrequired'):带有IF的客户案例3代码:函数getEventTarget(可能){如果(!可能){可能=window.event;}如果(!evt){返回;}常量目标;如果(可能。目标){目标=可能。目标;}其他{目标=如果。源元素;}returntarget;}重构代码:functiongetEventTarget(if){if=if||窗口.事件;returnif&&(if.target||if.srcElement);}带有IF的代码:constisOnline=true;constmakeReservation=()=>{};constuser={name:'Damian',age:32,dni:33295000};if(isOnline){makeReservation(user);}重构后的代码:constisOnline=true;constmakeReservation=()=>{};constuser={name:'Damian',age:32,dni:33295000};isOnline&&makeReservation(用户);带有IF代码的案例2:constactive=true;constloan={uuid:123456,ammount:10,requestedBy:'rick'};constsendMoney=()=>{};if(active&&loan){sendMoney()}重构代码:constactive=true;constloan={uuid:123456,ammount:10,requestedBy:'rick'};常量发送Money=()=>{};active&&loan&&sendMoney();3.函数委托:带有IF的案例1代码:functionitemDropped(item,location){if(!item){returnfalse;}elseif(outOfBounds(location){varerror=outOfBounds;server.notify(item,error);items.resetAll();returnfalse;}else{animateCanvas();server.notify(item,location);returntrue;}}重构代码:functionitemDropped(item,location){constdropOut=function(){server.notify(item,outOfBounds);items.resetAll();returnfalse;}constdropIn=function(){server.notify(item,location);animateCanvas();returntrue;}return!!item&&(outOfBounds(location)?dropOut():dropIn());}大家都说简历没项目可写,所以我给你找了个工程,还自带【搭建教程】我跟阿里云服务器合作,优惠价比较便宜:89/年,223/3年,比学生便宜9.9一个月,买了建个工程,熟悉用技术栈更香(老用户可以用家人号买,我用的是我妈的)推荐三年特价,点此查看。4.非-分支策略这种技术试图避免使用switch语句。相反,它使用键/值来创建一个Map并使用一个函数来访问作为参数传递的键的值。带有开关的案例1代码:switch(breed){case'border':return'BorderColliesaregoodboysandgirls.';休息;case'pitbull':return'PitBullsaregoodboysandgirls.';休息;case'german':return'德国牧羊犬是好男孩和好女孩。休息;default:return'Imdefault'}重构代码:constdogSwitch=(breed)=>({"border":"BorderColliesaregoodboysandgirls.","pitbull":"PitBullsaregoodboysandgirls.","german":"GermanShepherdsaregoodboysandgirls.",})[breed]||'我是默认的';dogSwitch("borderxxx")5.作为数据的函数,我们知道function是JS中的firstclass,所以我们可以使用它把代码分割成一个函数对象。带有IF的代码:constcalc={run:function(op,n1,n2){constresult;if(op=="add"){结果=n1+n2;}elseif(op=="sub"){结果=n1-n2;}elseif(op=="mult"){结果=n1*n2;}elseif(op=="div"){结果=n1/n2;}返回结果;}}calc.run("sub",5,3);//2重构代码:constcalc={add:function(a,b){returna+b;},sub:function(a,b){返回a-b;},mult:function(a,b){返回a*b;},div:function(a,b){返回a/b;},运行:function(fn,a,b){returnfn&&fn(a,b);}}calc.run(calc.mult,7,4);//286。多态性多态性是一个对象具有多种形式的能力。OOP中多态性最常见的用法是使用父类引用来引用子类对象。带有IF的代码:constbob={name:'Bob',salary:1000,job_type:'DEVELOPER'};constmary={name:'Mary',salary:1000,job_type:'QA'};constcalc=(person)=>{if(people.job_type==='DEVELOPER')returnperson.salary+9000*0.10;if(people.job_type==='QA')returnperson.salary+1000*0.60;}console.log('Salary',calc(bob));console.log('Salary',calc(mary));重构代码:constqaSalary=(base)=>base+9000*0.10;constdevSalary=(base)=>base+1000*0.60;//给对象添加函数.constbob={name:'Bob',salary:1000,job_type:'DEVELOPER',calc:devSalary};constmary={name:'Mary',salary:1000,job_type:'QA',calc:qaSalary};console.log('Salary',bob.calc(bob.salary));console.log('Salary',mary.计算(玛丽.薪水));代码部署后可能存在的bug,无法实时获知。事后为了解决这些bug,花费了大量的时间在日志调试上。顺便推荐一个好用的bug监控工具Fundebug。原文:https://dev.to/damxipo/avoid-...每周更新交流文章。可以微信搜索“大千世界”立即阅读更新(比博文早一两篇),本文的GitHubhttps://github.com/qq449245884/xiaozhi已经收录,还有很多我的文件已经整理好了。欢迎明星和完美。面试可以参考考点。也关注公众号,后台回复福利,就可以看到福利,你懂的。