Home Web Front-end JS Tutorial Example of writing using command object instead of switch statement_javascript skills

Example of writing using command object instead of switch statement_javascript skills

May 16, 2016 pm 04:12 PM
switch statement replace

Someone once said that a truly good program does not have if..else. Of course, switch is not as good as if..else. The use of switch is prohibited in the JS specification.

The command object perfectly solves this problem.

Quote from a foreign blog:

JavaScript has good control flow statements, which are often wrapped in curly braces. There is one exception: the switch … case statement. The strange thing about switch ... case is that you must add the break keyword at the end of each case to prevent flow control from passing into the next case statement. Traversal refers to the method of executing multiple cases. When the expected break is not encountered, control is automatically handed over to the next case. However, just like semicolons and braces, you may inadvertently forget to write break. When this happens, troubleshooting later will be more painful because the statement itself is correct. Therefore, it is a good practice to write case ... break in pairs.
We usually say that JavaScript has elegant object literals and top-level functions, which make specific method queries very simple. The objects created for method queries are called action objects or command objects, and are used in many software design patterns, including the powerful and useful command pattern.

Example:

Copy code The code is as follows:

// switch method
Function testSwitch(name) {
switch (name) {
case '1':
                    return 'hack';
                 break;
case '2':
                     return 'slash';
                 break;
case '3':
                    return 'run';
                 break;
                 default:
                       return false;
                 break;
}
}
//Use command object
Function testFn(name) {
      var names = {
              '1': function() {
                    return 'hack';
            },
              '2': function() {
                     return 'slash';
            },
              '3': function() {
                    return 'run';
            }
        };
If (typeof names[name] !== 'function') {
              return false;
}
          return names[name]();
}
// Test results
var result1 = testSwitch('1');
var result2 = testFn('2');
console.info(result1, result2);
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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

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)

Conditional control structures in PHP Conditional control structures in PHP Mar 10, 2024 pm 09:36 PM

Conditional control structure in PHP In PHP programming, conditional control structure is a very important syntax, which allows the program to execute different code blocks based on different conditions. By using conditional control structures, we can implement the branching logic of the program and determine the execution path of the program based on the result of the condition. This article will introduce the commonly used conditional control structures in PHP, including if statements, else statements, elseif statements and switch statements, and give specific code examples. The if statement is the most basic conditional control in PHP

Go language basics - switch statement Go language basics - switch statement Jul 24, 2023 pm 03:50 PM

switch is a conditional statement that is used to calculate the value of a conditional expression to determine whether the value satisfies the case statement. If it matches, the corresponding code block will be executed. Is a common way to replace complex if-else statements.

wifi7 can replace wired wifi7 can replace wired Dec 28, 2023 pm 07:44 PM

Many users are very concerned about the development of WiFi. When WiFi7 came out, many users began to speculate whether WiFi7 can replace the wired network. Of course, if WiFi can transmit at high speed and stably, then it is normal to replace the wired network. WiFi7 can replace the wired answer: It is expected to replace it. , but it depends on how it is officially put into use. WiFi7 is about 2 times faster than the previous generation WiFi6, and the delay has been reduced by nearly half. If it is possible to have very high-speed and stable transmission speeds, then it is normal to replace wired ones. Introduction to WiFi7 1. Wi-Fi7 is faster than Wi-Fi6. The industry defines it as "802.11beEHT", which means extremely high throughput 2. Wi-Fi7 can

switch statement switch statement Aug 11, 2023 am 10:54 AM

The switch statement is a control structure commonly used in programming, which allows the program to execute different code blocks based on different condition values. It can replace multiple if-else statements to improve the readability and maintainability of the code. Although it has some limitations, under the right circumstances, using the Switch statement can make programs more concise and efficient.

How to use switch statement in Go language? How to use switch statement in Go language? Jun 11, 2023 am 09:11 AM

Go language is an emerging programming language. It has the characteristics of efficiency, simplicity, security and concurrency, and is very suitable for use in fields such as web development, distributed systems and cloud computing. In the Go language, the switch statement is a very commonly used language structure, which can select different branches for execution based on the value of the expression. This article will introduce the basic usage and precautions of switch statements in Go language. Basic syntax: The switch statement in Go language is different from that in other programming languages.

How to use switch statement How to use switch statement Sep 21, 2023 pm 05:48 PM

Switch statement usage: 1. The Switch statement can only be used for integer types, enumeration types and String types, and cannot be used for floating point types and Boolean types; 2. Each case statement must be followed by a break statement to prevent other cases from being executed. The code block without a break statement will continue to execute the code block of the next case; 3. Multiple values ​​can be matched in one case statement, separated by commas; 4. The default code block in the Switch statement is optional, etc. wait.

Local variable type inference in Java 10: How to use final var keyword in switch statement Local variable type inference in Java 10: How to use final var keyword in switch statement Jul 31, 2023 pm 12:31 PM

Local variable type inference in Java10: How to use finalvar keyword in switch statement As the Java language continues to evolve, each new version introduces some new features and improvements. In Java10, one of the important new features is local variable type inference. This feature allows developers to use the var keyword instead of explicit type declarations, making the code more streamlined and readable. This article will explore how to use the finalvar switch in a switch statement.

How do Java enum types work with switch statements? How do Java enum types work with switch statements? Apr 30, 2024 pm 06:48 PM

Enumeration type is a data type in Java that defines a collection of constants. With the switch statement, the following functions can be achieved: Clearly represent the value range: The enumeration type is used to define a set of immutable constant values ​​to improve code readability. Matching different enumeration constants: The switch statement allows different operations to be performed based on the enumeration constants to achieve refined control. Handling different scenarios: Through enumeration types and switch statements, various situations can be flexibly handled in actual scenarios, such as sending different email contents according to different notification types.

See all articles