This article mainly introduces how to replace if-else and switch in js. It has certain reference value. Now I share it with everyone. Friends in need can refer to it
I believe many people have this experience. When the project is busy, they will consider implementation first and implement the solution in the best way at the time. When the project is not busy, they will look at the previous code and think about it. Is there any better implementation solution or optimization solution? The author is no exception. Let me share with readers my recent solution to replace if-else and switch in specific situations. If you have any ideas, please leave a message in the comment area and let us communicate more.
For example, you may encounter requirements similar to the following: For example, if the credit score rating of a certain platform exceeds 700-950, it means that the credit is excellent. , 650-700 has excellent credit, 600-650 has good credit, 550-600 has medium credit, and 350-550 has poor credit.
The implementation is very simple
function showGrace(grace) { let _level=''; if(grace>=700){ _level='信用极好' } else if(grace>=650){ _level='信用优秀' } else if(grace>=600){ _level='信用良好' } else if(grace>=550){ _level='信用中等' } else{ _level='信用较差' } return _level; }
There is no problem running, but there are also problems
1. In case of future needs, change the example 650-750 means excellent credit, and 750-950 means excellent credit. In this way, the entire method needs to be changed.
2. There are various magical numbers in the method: 700, 650, 600, 550. There may be problems with future maintenance.
3. There are too many if-else, which seems a bit obsessive-compulsive
So let’s use the look-up table to implement the separation of configuration data and business logic
function showGrace(grace) { let graceForLevel=[700,650,600,550]; let levelText=['信用极好','信用优秀','信用良好','信用中等','信用较差']; for(let i=0;i<graceforlevel.length>=graceForLevel[i]){ return levelText[i]; } } //如果不存在,那么就是分数很低,返回最后一个 return levelText[levelText.length-1]; }</graceforlevel.length>
The advantage of such a modification is that if there is a need to modify it, you only need to modify graceForLevel and levelText. The business logic does not need to be changed.
Why is it recommended to separate configuration data from business logic?1. Modifying configuration data is less expensive and less risky than modifying business logic
2. Both configuration data sources and modifications are possible Very flexible
3. It is recommended to separate configuration and business logic, so that you can find the code that needs to be modified faster
If you want to be more flexible, you can encapsulate a slightly more general look- up function.
function showGrace(grace,level,levelForGrace) { for(let i=0;i<level.length>=level[i]){ return levelForGrace[i]; } } //如果不存在,那么就是分数很低,返回最后一个 return levelForGrace[levelText.length-1]; } let graceForLevel=[700,650,600,550]; let levelText=['信用极好','信用优秀','信用良好','信用中等','信用较差'];</level.length>
There is another benefit of using the recommended separation of configuration data and business logic to develop, which is not reflected in the above example. Let’s briefly talk about it below. For example, enter an attraction and give the city where the attraction is located.
function getCityForScenic(scenic) { let _city='' if(scenic==='广州塔'){ _city='广州' } else if(scenic==='西湖'){ _city='杭州' } return _city; }
Enter Guangzhou Tower to return to Guangzhou. Enter West Lake and return to Hangzhou. But a city has more than one attraction, so some people are used to writing it like this.
if(scenic==='广州塔'||scenic==='花城广场'||scenic==='白云山'){ _city='广州' }
If there are many attractions and the data is very long, it looks uncomfortable. Some people like to write like this
let scenicOfHangZhou=['西湖','湘湖','砂之船生活广场','京杭大运河','南宋御街'] if(~scenicOfHangZhou.indexOf(scenic)){ _city='杭州' }
This execution is correct, but the code written It may be like the following, the style is not uniform.
function getCityForScenic(scenic) { let _city=''; let scenicOfHangZhou=['西湖','湘湖','砂之船生活广场','京杭大运河','南宋御街']; if(scenic==='广州塔'||scenic==='花城广场'||scenic==='白云山'){ _city='广州' } else if(~scenicOfHangZhou.indexOf(scenic)){ _city='杭州' } return _city; }
Even if you use switch, such a situation may occur
function getCityForScenic(scenic) { let _city=''; let scenicOfHangZhou=['西湖','湘湖','砂之船生活广场','京杭大运河','南宋御街']; switch(true){ case (scenic==='广州塔'||scenic==='花城广场'||scenic==='白云山'):_city='广州';break; case (!!~scenicOfHangZhou.indexOf(scenic)):return '杭州'; } return _city; }
Although the probability of the above code appearing is very small, it will happen after all. Such code may cause confusion in the future. This problem can be avoided if configuration data and business logic are separated.
function getCityForScenic(scenic) { let cityConfig={ '广州塔':'广州', '花城广场':'广州', '白云山':'广州', '西湖':'杭州', '湘湖':'杭州', '京杭大运河':'杭州', '砂之船生活广场':'杭州', '南宋御街':'杭州', } return cityConfig[scenic]; }
Some people are not used to the fact that the key name of an object is in Chinese. It can also be handled flexibly
function getCityForScenic(scenic) { let cityConfig=[ { scenic:'广州塔', city:'广州' }, { scenic:'花城广场', city:'广州' }, { scenic:'白云山', city:'广州' }, { scenic:'西湖', city:'杭州' }, { scenic:'湘湖', city:'杭州' }, { scenic:'京杭大运河', city:'杭州' }, { scenic:'砂之船生活广场', city:'杭州' } ] for(let i=0;i<cityconfig.length><p> In this way, if you want to add any attractions or corresponding cities in the future, you can only modify the cityConfig above. The business logic does not need to be changed, and it cannot be changed. The coding style is unified. </p> <p><strong> Here is a brief summary, the benefits of using a form of separation of configuration data and business logic</strong></p> <ol class=" list-paddingleft-2"> <li><p>The cost of modifying configuration data is less than modifying business logic , the risk is lower</p></li> <li><p>Configuration data sources and modifications can be very flexible</p></li> <li><p>Separation of configuration and business logic allows you to find modifications that need to be made faster The code</p></li> <li><p>Configuring data and business logic can make the code style unified</p></li> </ol> <blockquote>But not all if-else recommends such transformation, some It is not recommended to use look-up transformation according to requirements. For example, if there are not many if-else, and the logic of if judgment is not used uniformly, it is still recommended to use the if-else method. But the magic number needs to be cleared. </blockquote> <p>For example, the following example eliminates the incoming timestamp and displays the comment time display requirement. </p> <p><strong>Publish comments within 1 hour: x minutes ago</strong></p> <p> <strong>Publish comments from 1 hour to 24 hours: x hours ago </strong></p> <p><strong>Publish comments from 24 hours to 30 days: x days ago </strong></p> <p><strong>Comments posted more than 30 days ago: month/day</strong></p> <p><strong>Comments posted last year and more than 30 days old: year/month/day</strong></p> <p>It’s not difficult to achieve, Just a few if-else</p> <pre class="brush:php;toolbar:false">function formatDate(timeStr){ //获取当前时间戳 let _now=+new Date(); //求与当前的时间差 let se=_now-timeStr; let _text=''; //去年 if(new Date(timeStr).getFullYear()!==new Date().getFullYear()&&se>2592000000){ _text=new Date(timeStr).getFullYear()+'年'+(new Date(timeStr).getMonth()+1)+'月'+new Date(timeStr).getDate()+'日'; } //30天以上 else if(se>2592000000){ _text=(new Date(timeStr).getMonth()+1)+'月'+new Date(timeStr).getDate()+'日'; } //一天以上 else if(se>86400000){ _text=Math.floor(se/86400000)+'天前'; } //一个小时以上 else if(se>3600000){ _text=Math.floor(se/3600000)+'小时前'; } //一个小时以内 else{ //如果小于1分钟,就显示1分钟前 if(se<p style="text-align: center;"><img src="https://img.php.cn//upload/image/382/741/424/1531706091492473.jpg" title="1531706091492473.jpg" alt="How to replace if-else and switch in js"></p><p>运行结果没问题,但是也存在一个问题,就是这个需求有神仙数字:2592000000,86400000,3600000,60000。对于后面维护而言,一开始可能并不知道这个数字是什么东西。</p><p>所以下面就消灭神仙数字,常量化</p><pre class="brush:php;toolbar:false">function formatDate(timeStr){ //获取当前时间戳 let _now=+new Date(); //求与当前的时间差 let se=_now-timeStr; const DATE_LEVEL={ month:2592000000, day:86400000, hour:3600000, minter:60000, } let _text=''; //去年 if(new Date(timeStr).getFullYear()!==new Date().getFullYear()&&se>DATE_LEVEL.month){ _text=new Date(timeStr).getFullYear()+'年'+(new Date(timeStr).getMonth()+1)+'月'+new Date(timeStr).getDate()+'日'; } //一个月以上 else if(se>DATE_LEVEL.month){ _text=(new Date(timeStr).getMonth()+1)+'月'+new Date(timeStr).getDate()+'日'; } //一天以上 else if(se>DATE_LEVEL.day){ _text=Math.floor(se/DATE_LEVEL.day)+'天前'; } //一个小时以上 else if(se>DATE_LEVEL.hour){ _text=Math.floor(se/DATE_LEVEL.hour)+'小时前'; } //一个小时以内 else{ //如果小于1分钟,就显示1分钟前 if(se<date_level.minter><p>运行结果也是正确的,代码多了,但是神仙数字没了。可读性也不差。</p> <blockquote>这里也顺便提一下,如果硬要把上面的需求改成look-up的方式,代码就是下面这样。这样代码的修改的扩展性会强一些,成本会小一些,但是可读性不如上面。取舍关系,实际情况,实际分析。</blockquote> <pre class="brush:php;toolbar:false">function formatDate(timeStr){ //获取当前时间戳 let _now=+new Date(); //求与当前的时间差 let se=_now-timeStr; let _text=''; //求上一年最后一秒的时间戳 let lastYearTime=new Date(new Date().getFullYear()+'-01-01 00:00:00')-1; //把时间差添加进去(当前时间戳与上一年最后一秒的时间戳的差)添加进去,如果时间差(se)超过这个值,则代表了这个时间是上一年的时间。 //DATE_LEVEL.unshift(_now-lastYearTime); const DATE_LEVEL={ month:2592000000, day:86400000, hour:3600000, minter:60000, } let handleFn=[ { time:DATE_LEVEL.month, fn:function(timeStr){ return (new Date(timeStr).getMonth()+1)+'月'+new Date(timeStr).getDate()+'日'; } }, { time:DATE_LEVEL.day, fn:function(timeStr){ return Math.floor(se/DATE_LEVEL.day)+'天前'; } }, { time:DATE_LEVEL.hour, fn:function(timeStr){ return Math.floor(se/DATE_LEVEL.hour)+'小时前'; } }, { time:DATE_LEVEL.minter, fn:function(timeStr){ return Math.ceil(se/DATE_LEVEL.minter)+'分钟前'; } } ]; //求上一年最后一秒的时间戳 let lastYearTime=new Date(new Date().getFullYear()+'-01-01 00:00:00')-1; //把时间差(当前时间戳与上一年最后一秒的时间戳的差)和操作函数添加进去,如果时间差(se)超过这个值,则代表了这个时间是上一年的时间。 handleFn.unshift({ time:_now-lastYearTime, fn:function(timeStr){ if(se>DATE_LEVEL.month){ return new Date(timeStr).getFullYear()+'年'+(new Date(timeStr).getMonth()+1)+'月'+new Date(timeStr).getDate()+'日'; } }, }); let result=''; for(let i=0;i<handlefn.length>=handleFn[i].time){ result=handleFn[i].fn(timeStr); if(result){ return result; } } } //如果发布时间小于1分钟,之际返回1分钟 return result='1分钟前' }</handlefn.length>
比如有一个需求:传入cash,check,draft,zfb,wx_pay,对应输出:现金,支票,汇票,支付宝,微信支付。
需求也很简单,就一个switch就搞定了
function getPayChanne(tag){ switch(tag){ case 'cash':return '现金'; case 'check':return '支票'; case 'draft':return '汇票'; case 'zfb':return '支付宝'; case 'wx_pay':return '微信支付'; } }
但是这个的硬伤还是和上面一样,万一下次又要多加一个如:bank_trans对应输出银行转账呢,代码又要改。类似的问题,同样的解决方案,配置数据和业务逻辑分离。代码如下。
function getPayChanne(tag){ let payChanneForChinese = { 'cash': '现金', 'check': '支票', 'draft': '汇票', 'zfb': '支付宝', 'wx_pay': '微信支付', }; return payChanneForChinese[tag]; }
同理,如果想封装一个通用的,也可以的
let payChanneForChinese = { 'cash': '现金', 'check': '支票', 'draft': '汇票', 'zfb': '支付宝', 'wx_pay': '微信支付', }; function getPayChanne(tag,chineseConfig){ return chineseConfig[tag]; } getPayChanne('cash',payChanneForChinese);
这里使用对象代替 switch 好处就在于
使用对象不需要 switch 逐个 case 遍历判断。
使用对象,编写业务逻辑可能更灵活
使用对象可以使得配置数据和业务逻辑分离。好处参考上一部分内容。
以上就是本文的全部内容,希望对大家的学习有所帮助,更多相关内容请关注PHP中文网!
相关推荐:
The above is the detailed content of How to replace if-else and switch in js. For more information, please follow other related articles on the PHP Chinese website!