Detailed explanation of the usage of Switch statement in JavaScript
In addition to if...else, JavaScript also has a feature called a switch statement. A switch is a conditional statement that will evaluate an expression against a number of possible situations and execute one or more blocks of code depending on the matching situation. The switch statement is closely related to the conditional statement that contains many other if blocks, and they are often used interchangeably.
In this tutorial, we will learn how to use the switch statement and how to use the related keywords case, break and default. Finally, we'll cover how to use multiple cases in a switch statement.
[Related course recommendations: JavaScript video tutorial]
Switch
switch statement calculation expression formula and execute the code as the result of matching case. It may seem a little intimidating at first, but the basic syntax is similar to an if statement. It will always be written using switch(){}, with parentheses containing the expression to be tested, and curly braces containing the underlying code to be executed.
The following is an example of a switch statement with two case statements and a fallback called default.
switch (expression) { case x: // execute case x code block break; case y: // execute case y code block break; default: // execute default code block }
Following the logic of the code block above, this is the sequence of events that will occur:
Expression is evaluated
In the first case, x will be tested against the expression . If there is a match, the code will execute and the break keyword will end the switch block.
If it does not match, x will be skipped and y will be tested against the expression case. If y matches the expression, the code will execute and exit the switch block.
If all conditions are not matched, the default code block will be run.
Let’s make a working example of a switch statement following the above syntax. In this code block, we will use the new Date() method to find the current day of the week and getDay() to print the number corresponding to the current day. 1 stands for Monday and 7 stands for Sunday. We'll start by setting up variables.
const day = new Date().getDay();
Using switch we will send a message to the console every day of the week. The program will run in order from top to bottom looking for matches, and once one is found, the break command will stop the switch block and continue evaluating the statement.
week.js
// Set the current day of the week to a variable, with 1 being Monday and 7 being Sunday const day = new Date().getDay(); switch (day) { case 1: console.log("Happy Monday!"); break; case 2: console.log("It's Tuesday. You got this!"); break; case 3: console.log("Hump day already!"); break; case 4: console.log("Just one more day 'til the weekend!"); break; case 5: console.log("Happy Friday!"); break; case 6: console.log("Have a wonderful Saturday!"); break; case 7: console.log("It's Sunday, time to relax!"); break; default: console.log("Something went horribly wrong..."); }
Output 'Just one more day 'til the weekend!'
This code was tested on Thursday, which corresponds to 4, so the console output is Just one more day 'til the weekend!. Depending on the day of the week you test your code, your output will vary. We include a block by default at the end to run in case of an error, which should not happen in this case since there are only 7 days in a week. For example, we might also only have print results from Monday to Friday, and the default block might have the same information for weekends as well.
If we omit the break keyword in each statement, none of the other case statements will evaluate to true, but the program will continue checking until it reaches the end. To make our program faster and more efficient, we include break.
Switch Ranges
There is a situation where you need to evaluate a range of values in a switch block instead of like in the example above single value. We can do this by setting the expression to true and performing the action in each case statement.
To make this easier to understand, we made a simple grading app that will take a numeric score and convert it to a letter grade, with the following requirements.
● Level 90 and above is A
● Level 80 to 89 is B
● Level 70 to 79 is C
● Level 60 to 69 is D
● Level 59 or below is F
Now we can write it as a switch statement. Since we are checking the range, we will do something in each case to check if each expression is evaluating to true, and then break out the statement once the true requirement is met.
grades.js
// Set the student's grade const grade = 87; switch (true) { // If score is 90 or greater case grade >= 90: console.log("A"); break; // If score is 80 or greater case grade >= 80: console.log("B"); break; // If score is 70 or greater case grade >= 70: console.log("C"); break; // If score is 60 or greater case grade >= 60: console.log("D"); break; // Anything 59 or below is failing default: console.log("F"); }
Output 'B'
In this example, the expression in the brackets is evaluated to true. This means that anything that evaluates to true is a match.
Just like using else, switch evaluates from top to bottom and accepts the first true match. So even though our rank variable is 87 and therefore evaluates to true for C and D, the first match is B and it will be the output.
Multiple Cases
You may encounter code where multiple cases should have the same output. To achieve this, you can use multiple cases for each code block.
To test this, we will make a small application that matches the current month with the appropriate season. First, we will use the new Date() method to find the number corresponding to the current month and apply it to the month variable.
For simplicity, our application will output the four seasons with the following specifications:
● Winter: January, February and March
● Spring: April , May and June
●Summer: July, August and September
●Autumn: October, November and December
以下是我们的代码。
seasons.js
// Get number corresponding to the current month, with 0 being January and 11 being December const month = new Date().getMonth(); switch (month) { // January, February, March case 0: case 1: case 2: console.log("Winter"); break; // April, May, June case 3: case 4: case 5: console.log("Spring"); break; // July, August, September case 6: case 7: case 8: console.log("Summer"); break; // October, November, December case 9: case 10: case 11: console.log("Autumn"); break; default: console.log("Something went wrong."); }
当我们运行代码时,我们将根据上面的规范接收识别当前季节的输出。
Output Summer
出版时的当月是8,这与“夏季”季节产出的一个case陈述相对应。
结论:
在本文中,我们回顾了switch语句,这是一种条件语句,用于评估表达式并根据匹配结果输出不同的值。 我们使用范围和多个case语句检查了switch语句。
本文来自 js教程 栏目,欢迎学习!
The above is the detailed content of Detailed explanation of the usage of Switch statement in JavaScript. For more information, please follow other related articles on the PHP Chinese website!

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.


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

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Atom editor mac version download
The most popular open source editor

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

Dreamweaver Mac version
Visual web development tools

Notepad++7.3.1
Easy-to-use and free code editor