Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How js replaces if/else with switch case

2025-04-02 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article is about how js replaces if/else with switch case. The editor thinks it is very practical, so share it with you as a reference and follow the editor to have a look.

Replace if/else with switch case

Switch case performs better than if/else, and the code looks clearer.

If (1 = = month) {days = 31;} else if (2 = = month) {days = IsLeapYear (year)? 29: 28;} else if (3 = = month) {days = 31;} else if (4 = = month) {days = 30;} else if (5 = = month) {days = 31;} else if (6 = = month) {days = 30;} else if (7 = month) {days = 31;} else if (8 = month) {days = 31;} else if (9 = month) {days = 30 } else if (10 = = month) {days = 31;} else if (11 = = month) {days = 30;} else if (12 = = month) {days = 31;}

Use switch...case to overwrite:

Switch (month) {case 1: days = 31; break; case 2: days = IsLeapYear (year)? 29: 28; break; case 3: days = 31; break; case 4: days = 30; break; case 5: days = 31; break; case 6: days = 30; break; case 7: days = 31; break; case 8: days = 31; break; case 9: days = 30; break Case 10: days = 31; break; case 11: days = 30; break; case 12: days = 31; break; default: break;}

It looks a little more concise. You can rewrite if...else using arrays or objects as appropriate.

Thank you for reading! This is the end of this article on "how js uses switch case to replace if/else". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, you can share it for more people to see!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report