Process control statement switch select statement

Keywords: Javascript

When there are many options, switch is more convenient than if else. The syntax is as follows:

 1 switch (expression)
 2 {
 3 case value 1:
 4 execution code block 1
 5   break;
 6 case value 2:
 7 execution code block 2
 8   break;
 9 ...
10 case value n:
11 execution code block n
12   break;
13 default:
14 code executed at the same time as case value 1, case value 2...case value n
15 }

Syntax description:

1 the switch must be assigned an initial value that matches each case value. Satisfy all statements after executing the case, and use the break statement to prevent the next case from running. If all case values do not match, execute the statement after default.

For example: suppose to evaluate the test results of students, the 10 point full score system, we grade the scores according to each grade, and make different evaluations according to the grades of the scores.

 1 <!DOCTYPE >
 2 <html>
 3     <head>
 4         <title>switch Sentence</title>
 5         <meta charset="utf-8">
 6         <script type="text/javascript">
 7         var myscore=5;
 8         switch(myscore){
 9             case 0:
10             case 1:
11             case 2:
12             case 3:
13             case 4:
14             case 5:
15             degree="Keep trying!";
16             document.write('Comment:'+degree+"<br />");
17             // break;
18             case 6:
19             degree="Pass, come on!"
20             document.write('Comment:'+degree+"<br />");
21             break;
22             case 7:
23             degree="Make do, fight!"
24             document.write('Comment:'+degree+"<br />");
25             break;
26             case 8:
27             degree="MMD, bangbangbangdi"
28             document.write('Comment:'+degree+"<br />");
29             break;
30             case 9:
31             case 10:
32             degree="You're as good as me"
33             document.write('Comment:'+degree+"<br />");
34             break;
35         }
36         </script>
37     </head>
38     <body>
39     </body>
40 </html>

Note that the last break statement is added after the statement executed by the case. Otherwise, directly continue to execute the following statements in case. The final comment shown in the code above is:

1 comment: continue to work hard!
Comment: pass, come on!

Posted by SirChick on Thu, 16 Apr 2020 08:02:20 -0700