Table of Contents
1️⃣ Simple branch optimization
2️⃣ Complex branch optimization
3️⃣ Detach branch
4️⃣ Controversy
? Conclusion
Home Web Front-end JS Tutorial One article teaches you how to implement JavaScript if branch optimization

One article teaches you how to implement JavaScript if branch optimization

Mar 14, 2023 pm 07:37 PM
javascript if-else

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!

One article teaches you how to implement JavaScript if branch optimization

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("此人比较神秘!");
    }
}
Copy after login

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("此人比较神秘!");
}
Copy after login

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("此人比较神秘!");
    }
}
Copy after login

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("此人比较神秘!");
}
Copy after login

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("此人比较神秘!");
}
Copy after login
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("此人比较神秘!");
}
Copy after login

Through modular development, you can also write this map object into a separate js 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("此人比较神秘!");
}
Copy after login

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;
}
Copy after login

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 (getUserDescribeFunctionThe 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;
}
Copy after login
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 example

describeForNameMapThe 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 the object/array is still more wasteful than simply if else.
  • Viewpoint 2: The code after branch optimizationreadability/maintainability is better, and the introduction of object/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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

How to use JavaScript and WebSocket to implement a real-time online ordering system How to use JavaScript and WebSocket to implement a real-time online ordering system Dec 17, 2023 pm 12:09 PM

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

How to implement an online reservation system using WebSocket and JavaScript How to implement an online reservation system using WebSocket and JavaScript Dec 17, 2023 am 09:39 AM

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

JavaScript and WebSocket: Building an efficient real-time weather forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

How to use insertBefore in javascript How to use insertBefore in javascript Nov 24, 2023 am 11:56 AM

Usage: In JavaScript, the insertBefore() method is used to insert a new node in the DOM tree. This method requires two parameters: the new node to be inserted and the reference node (that is, the node where the new node will be inserted).

JavaScript and WebSocket: Building an efficient real-time image processing system JavaScript and WebSocket: Building an efficient real-time image processing system Dec 17, 2023 am 08:41 AM

JavaScript is a programming language widely used in web development, while WebSocket is a network protocol used for real-time communication. Combining the powerful functions of the two, we can create an efficient real-time image processing system. This article will introduce how to implement this system using JavaScript and WebSocket, and provide specific code examples. First, we need to clarify the requirements and goals of the real-time image processing system. Suppose we have a camera device that can collect real-time image data

See all articles