


One article teaches you how to implement JavaScript if branch optimization
1000 judgment conditions require writing 1000 ifs? How to optimize if branch statement? The following article will talk to you about how to achieve branch optimization. I hope it will be helpful to everyone!
I recently saw this piece of code while surfing the Internet:
function getUserDescribe(name) { if (name === "小刘") { console.log("刘哥哥"); } else if (name === "小红") { console.log("小红妹妹"); } else if (name === "陈龙") { console.log("大师"); } else if (name === "李龙") { console.log("师傅"); } else if (name === "大鹏") { console.log("恶人"); } else { console.log("此人比较神秘!"); } }
At first glance, I didn’t feel anything unusual, but if there are 1000 judgment conditions, Is it difficult to write 1,000 if
branches according to this way of writing?
If you write a large number of if
branches, and may also have branches within branches, you can imagine that the readability and maintainability of the entire code will be greatly reduced. This is indeed a headache in actual development. Is there any way to achieve the requirements while avoiding these problems? [Recommended learning: javascript video tutorial]
1️⃣ Simple branch optimization
This involves branch optimization, let Let’s change our thinking and optimize the above code structure:
function getUserDescribe(name) { const describeForNameMap = { 小刘: () => console.log("刘哥哥"), 小红: () => console.log("小红妹妹"), 陈龙: () => console.log("大师"), 李龙: () => console.log("师傅"), 大鹏: () => console.log("恶人"), }; describeForNameMap[name] ? describeForNameMap[name]() : console.log("此人比较神秘!"); }
The judgments in the problem code are all simple Equal judgment, then we can write these judgment conditions as an attribute In the object describeForNameMap
, the values corresponding to these attributes are the processing functions after the conditions are established.
After that, we only need to obtain the corresponding value in the describeForNameMap
object through the parameters received by the getUserDescribe
function. If the value exists, run the value (because the value is a function).
In this way, the original if
branch judgment is converted into a simple key value
corresponding value. The conditions and processing functions correspond one to one, making it clear at a glance.
2️⃣ Complex branch optimization
Then if the judgment condition in our if
branch is not just a simple equality judgment, but also has some calculations that need to be calculated What should we do when the expression is ? (As shown below)
function getUserDescribe(name) { if (name.length > 3) { console.log("名字太长"); } else if (name.length < 2) { console.log("名字太短"); } else if (name[0] === "陈") { console.log("小陈"); } else if (name[0] === "李" && name !== "李鹏") { console.log("小李"); } else if (name === "李鹏") { console.log("管理员"); } else { console.log("此人比较神秘!"); } }
For code with this structure, objects cannot be introduced for branch optimization. We can introduce two-dimensional arrays for branch optimization:
function getUserDescribe(name) { const describeForNameMap = [ [ (name) => name.length > 3, // 判断条件 () => console.log("名字太长") // 执行函数 ], [ (name) => name.length < 2, () => console.log("名字太短") ], [ (name) => name[0] === "陈", () => console.log("小陈") ], [ (name) => name === "大鹏", () => console.log("管理员") ], [ (name) => name[0] === "李" && name !== "李鹏", () => console.log("小李"), ], ]; // 获取符合条件的子数组 const getDescribe = describeForNameMap.find((item) => item[0](name)); // 子数组存在则运行子数组中的第二个元素(执行函数) getDescribe ? getDescribe[1]() : console.log("此人比较神秘!"); }
Above we defined an describeForNameMap
array. Each element in the array represents a set of judgment conditions and execution functions (also an array). Then we use the find
method of the array. Just find the subarray in the describeForNameMap
array that meets the judgment conditions.
3️⃣ Detach branch
The describeForNameMap
object we defined in the above example is an independent structure, and we can completely detach it Go out:
const describeForNameMap = { 小刘: () => console.log("刘哥哥"), 小红: () => console.log("小红妹妹"), 陈龙: () => console.log("大师"), 李龙: () => console.log("师傅"), 大鹏: () => console.log("恶人"), }; function getUserDescribe(name) { describeForNameMap[name] ? describeForNameMap[name]() : console.log("此人比较神秘!"); }
const describeForNameMap = [ [ (name) => name.length > 3, // 判断条件 () => console.log("名字太长") // 执行函数 ], [ (name) => name.length < 2, () => console.log("名字太短") ], [ (name) => name[0] === "陈", () => console.log("小陈") ], [ (name) => name === "大鹏", () => console.log("管理员") ], [ (name) => name[0] === "李" && name !== "李鹏", () => console.log("小李"), ], ]; function getUserDescribe(name) { // 获取符合条件的子数组 const getDescribe = describeForNameMap.find((item) => item[0](name)); // 子数组存在则运行子数组中的第二个元素(执行函数) getDescribe ? getDescribe[1]() : console.log("此人比较神秘!"); }
Through modular development, you can also write this
map
object into a separatejs
file, and then import it wherever you need to use it. That’s it.
4️⃣ Controversy
In this way, the entire getUserDescribe
function becomes very concise. Some students may ask what’s the point of this? What to use? Isn't this more troublesome? If if else
really doesn’t look good, then I will use if return
instead of else
:
function getUserDescribe(name) { if (name === "小刘") { console.log("刘哥哥"); return; } if (name === "小红") { console.log("小红妹妹"); return; } if (name === "陈龙") { console.log("大师"); return; } if (name === "李龙") { console.log("师傅"); return; } if (name === "大鹏") { console.log("恶人"); return; } console.log("此人比较神秘!"); }
Just imagine, if There are 1000 judgment branches in your getUserDescribe
function, and there are also a large number of processing codes that are executed based on the judgment results, and the getUserDescribe
function will return the value of this processed judgment result.
At this time, the focus
of the getUserDescribe function lies in the processing of the judgment result, not in which branch the result is obtained, for example :
function getUserDescribe(name) { let str; // 存储判断结果 if (name.length > 3) { str = "名字太长"; } else if (name.length < 2) { str = "名字太短"; } else if (name[0] === "陈") { str = "小陈"; } else if (name[0] === "李" && name !== "李鹏") { str = "小李"; } else if (name === "李鹏") { str = "管理员"; } else { str = "此人比较神秘!"; } // 对判断结果str的一些处理 // ...... console.log(str); return str; }If you do not perform branch optimization, the
getUserDescribe function will be occupied by a large number of
if branches, making the
getUserDescribe function the focus of Lost (
getUserDescribeFunction
The focus is on the processing of the judgment result, not on which branch the result is obtained through), then you can take a look at our optimized code:
const describeForNameMap = [ [(name) => name.length > 3, () => "名字太长"], [(name) => name.length < 2, () => "名字太短"], [(name) => name[0] === "陈", () => "小陈"], [(name) => name === "大鹏", () => "管理员"], [(name) => name[0] === "李" && name !== "李鹏", () => "小李"], ]; function getUserDescribe(name) { let str; // 存储判断结果 const getDescribe = describeForNameMap.find((item) => item[0](name)); if (getDescribe) { str = getDescribe[1](); } else { str = "此人比较神秘!"; } // 对判断结果str的一些处理 // ...... console.log(str); return str; }Looking at the optimized
getUserDescribe function we can know that it obtains a value from
describeForNameMap and assigns it to
str (
describeForNameMap We don't care how returns the value), and then did some processing on
str. This highlights the focus of the
getUserDescribe function (
processing the judgment result str).
In this exampledescribeForNameMap
The second element of the subarray can directly use a value:
[(name) => name.length > 3 , "Name is too long"], but for the scalability of the overall code, it is recommended to use functions, because functions can receive parameters, making it easier to deal with more complex scenarios in the future.
? Conclusion
Branch optimizationThere are different implementation methods and application scenarios in various languages. This article uses JavaScript
Introduces two ideas of code branch optimization. The implementation of the code is very simple, and the focus is on the application of this idea.
In fact, there has been controversy about the issue of branch optimization. There are currently two views:
-
View 1: There is no need to bother optimizing it, and optimizing it Because the following code creates an extra
object/array
, retrieving theobject/array
is still more wasteful than simplyif else
. -
Viewpoint 2: The code after branch optimization
readability/maintainability
is better, and the introduction ofobject/array
brings Performance issues are simply not worth mentioning in this day and age.
What is your opinion?
For more programming-related knowledge, please visit: Programming Teaching! !
The above is the detailed content of One article teaches you how to implement JavaScript if branch optimization. For more information, please follow other related articles on the PHP Chinese website!

JavaScriptusestwotypesofcomments:single-line(//)andmulti-line(//).1)Use//forquicknotesorsingle-lineexplanations.2)Use//forlongerexplanationsorcommentingoutblocksofcode.Commentsshouldexplainthe'why',notthe'what',andbeplacedabovetherelevantcodeforclari

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Dreamweaver Mac version
Visual web development tools

Dreamweaver CS6
Visual web development tools

SublimeText3 Chinese version
Chinese version, very easy to use
