Scope matching usage of switch in js

https://www.cnblogs.com/qianxiaox/p/14085873.html How to ...

https://www.cnblogs.com/qianxiaox/p/14085873.html

How to use Switch statements in JavaScript

In addition to if... Else, JavaScript has a function called switch statement. Switch is a conditional statement that evaluates an expression for a variety of possible situations and executes one or more code blocks based on the match. Switch statements are closely related to conditional statements that contain many other if blocks, and they are often used interchangeably.

In this tutorial, we will learn how to use switch statements and how to use the related keywords case, break and default. Finally, we'll show you how to use multiple cases in a switch statement.

Switch

Switch statementevaluates an expression and executes code as a result of matching case. At first it looks a bit daunting, but the basic syntax is similar to if statements. It will always be written in switch () {}, with parentheses containing the expression to test and curly braces containing the potential code to execute.

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 above code block, this is the sequence of events to occur:

The expression is evaluated

The first case, x, tests 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 skip and y will test the case against the expression. If y matches the expression, the code executes and exits the switch block.

If all conditions do not match, the default code block runs.

Let's make a working example of a switch statement according to the above syntax. In this code block, we will use the new Date () method to find the current Date of the week and use getDay () to print the number corresponding to the day. 1 stands for Monday and 7 stands for Sunday. We'll start by setting variables.

const day = new Date().getDay();

Using switch, we will send messages to the console every day of the week. The program will run from top to bottom to find a match. Once one is found, the break command will stop the switch block and continue to evaluate 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, corresponding to 4, so the console output is Just one more day 'til the weekend!. Your output will vary depending on the day of the week you test the code. We default to include a block at the end to run when an error occurs, which should not happen in this case, because there are only 7 days a week. For example, we may only have print results from Monday to Friday, and the default block may have the same information on weekends.

If we omit the break keyword in each statement, the other case statements will not be evaluated as true, but the program will continue to check until it reaches the end. In order to make our program faster and more efficient, we include break.

Switch Ranges

In some cases, you need to evaluate a series of values in the switch block instead of a single value like the example above. We can do this by setting the expression to true and performing the operation in each case statement.

In order to make this easier to understand, we have made a simple scoring application, which will obtain a numeric score and convert it into an alphabetic grade, with the following requirements.

Grade 90 and above is A

Grades 80 to 89 are B

Grades 70 to 79 are C

Grades 60 to 69 are D

Grade 59 or below is F

Now we can write it as a switch statement. Since we are checking the scope, we will perform operations in each case to check whether each expression is evaluating as true, and then break through the statement after meeting the true requirement.

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 parentheses to evaluate is true. This means that anything evaluated as true will match.

Just as with else, switch evaluates from top to bottom and accepts the first real match. Therefore, even if our level variable is 87, it is evaluated as true for C and D. the first match is B, which will be the output.

Guangzhou brand design companyhttps://www.houdianzi.com PPT template downloadhttps://redbox.wode007.com

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'll 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 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

Here is our code.

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."); }

When we run the code, we will receive the output identifying the current season according to the above specification.

Output Summer

The month of publication is 8, which corresponds to a case statement produced during the "summer" season.

Conclusion:

In this article, we reviewed the switch statement, which is a conditional statement used to evaluate expressions and output different values according to the matching results. We examined the switch statement using a scope and multiple case statements.

28 October 2021, 05:31 | Views: 3720

Add new comment

For adding a comment, please log in
or create account

0 comments