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 to optimize the structure of if-else code

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

Share

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

This article focuses on "how to optimize the structure of if-else code", interested friends may wish to take a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn how to optimize the structure of if-else code.

Demand

Write a returnWeekday () method that returns "Today is the week *".

Next, we'll take it one step at a time.

Optimization process

Here I am simply divided into "beginner-> beginner-> Intermediate" stages.

Beginner

When we start to get the requirements, we see a series of logical judgments, and the first thing that comes to mind is the if statement.

The code is as follows:

Function returnWeekday () {let string = "Today is the week"; let date = new Date (). GetDay (); if (date = 0) {string + = "Day";} else if (date = 1) {string + = "one";} else if (date = 2) {string + = "two" } else if (date = 3) {string + = "three";} else if (date = 4) {string + = "four";} else if (date = 5) {string + = "five";} else if (date = 6) {string + = "six";} return string} console.log (returnWeekday ())

When we finish writing code like this, the first feeling is whether there are too many elseif blocks.

But while we are still thinking about how to optimize, the product is nailing and sending you a message asking how the requirement is being completed. And brought a bad smile meme. At this time, you tell yourself, let's talk about this optimization later. But over time, demand plus. This is no longer optimized until the next one takes over.

The above code does have too many elseif blocks, which makes it uncomfortable to look at it.

When we were watching JavaScript Advanced programming, we saw the following sentence:

Switch statement is most closely related to if statement, and it is also a kind of flow control statement commonly used in other languages.

So can we consider using the switch statement to optimize it?

Introduction

Here we use the switch statement to optimize the code.

Note: switch statements use congruent operators when comparing values, and there is no type conversion.

The code is as follows:

Function returnWeekday () {let string = "Today is the week"; let date = new Date (). GetDay (); switch (date) {case 0: string + = "Day"; break; case 1: string + = "one"; break Case 2: string + = "two"; break; case 3: string + = "three"; break; case 4: string + = "four"; break; case 5: string + = "five"; break Case 6: string + = "six"; break;} return string} console.log (returnWeekday ())

We concatenate characters in case in order to output the expected results. The structure here does look a little clearer than the if statement. But still a little confused?

Suppose that one day, the relevant organizations will find that the astrology has changed. It needs to be eight days a week (the thinking of the product, you can't imagine). Our returnWeekday () method needs an extra layer of judgment.

Our hope is that the method that has been encapsulated will not be modified frequently. But the change in demand is beyond your control.

So we continue to think about how to optimize it.

intermediate

We see that the case here is a number, which is consistent with the subscript of the array.

That is, the subscript of ['days', 'one', 'two', 'three', 'four', 'five', 'six'].

So we can consider using arrays to optimize.

The code is as follows:

Function returnWeekday () {let string = "Today is the week"; let date = new Date (). GetDay (); / use the array let dateArr = ['days', 'one', 'two', 'three', 'four', 'five', 'six']; return string + dateArr [date]} console.log (returnWeekday ())

The above code is much clearer than switch statement and if statement. And even if a week becomes eight days, you only need to modify the dateArr array.

What if each of our case is an irregular string? So we use objects, each case is a key.

The code is as follows:

Function returnWeekday () {let string = "Today is the week"; let date = new Date () .getDay () / / use object dateObj = {0: 'days', 1: "one", 2: "two", 3: "three", 4: "four", 5: "five", 6: "six",} Return string + dateObj [date]} console.log (returnWeekday ())

The above uses arrays or objects to improve the readability of the code and makes it easier to maintain.

Use the charAt character method

Strings have a method similar to using array subscripts:

/ / charAt location method function returnWeekday () {return "Today is week" + "Day 123456" .charat (new Date (). GetDay ());} console.log (returnWeekday ())

Demand change

At this point, someone wants the returnWeekday () method not only to return what day it is today, but also to distinguish between working days and rest days and call the relevant methods.

It's a bit of a hassle to maintain using switch, if, or arrays, and there's a lot of rewriting to do.

Function returnWeekday () {let string = "Today is the week"; let date = new Date () .getDay () / / use object dateObj = {0: ['days', 'Hugh'], 1: ["one", "Gong"], 2: ["2", "Gong"], 3: ["3", "Gong"], 4: ["4", "Gong"] "five", "Gong", 6: "six", "Hugh",} / / Type Here you can also correspond to the related method dayType = {'Hugh': function () {/ / some code console.log ('for rest day')} 'Gong': function () {/ / some code console.log ('for working days')} let returnData = {'string': string + dateObj [date] [0],' method': dayType [dateObj] [1]]} return returnData} Console.log (returnWeekday () .method.call (this))

Other common optimization methods

Here are some common optimization methods.

Ternary operation

Suitable for simple if () {} else {} cases.

/ / Scroll listening, fixed handleScroll: function () {let offsetTop = this.$refs.pride_tab_fixed.getBoundingClientRect (). Top; if (offsetTop < 0) {this.titleFixed = true} else {this.titleFixed = false} / / changed to ternary (offsetTop < 0)? This.titleFixed = true: this.titleFixed = false; / / We find that the assignment in the condition block is a Boolean value, so it can be more simple this.titleFixed = offsetTop < 0;}

In this way, there is no reduction in readability when streamlining the code.

Logic and operator

Sometimes we can use logic and operators to simplify the code.

If (falg) {someMethod ()}

It can be changed to:

Falg & & someMethod ()

Using includes to handle multiple conditions

If (code = = '202' | | code =' 203' | | code = '204') {someMethod ()}

It can be changed to

If (['202 someMethod () {someMethod ()} at this point, I believe you have a deeper understanding of "how to optimize the structure of if-else code". You might as well do it in practice! Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

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