[JavaScript] switch statement

switch means "switch", it is also a "select" statement, but its usage is very simple.
switch is a multi-branch select statement. To put it plainly, multiple branches are multiple ifs.

Functionally, the switch statement and if statement can completely replace each other.
But from the perspective of programming, they have their own characteristics, so it can not be said that who can completely replace who.

当嵌套的 if 比较少时(三个以内),用 if 编写程序会比较简洁。

However, when there are many branches selected, there will be many layers of nested if statements, resulting in lengthy programs and reduced readability.
Therefore, the C language provides switch statements to handle multi-branch selection.
So if and switch can be said that the division of labor is clear.
In many large projects, the situation of multi-branch selection is often encountered,
so the switch statement is still used more. The general form of the switch is as follows:

switch(n)
{
    case 1:
        执行代码块 1
        break;
    case 2:
        执行代码块 2
        break;
    default:case 1case 2 不同时执行的代码
}

How it works: First set the expression n (usually a variable). Then the value of the expression will be compared with the value of each case in the structure. If there is a match, the code block associated with the case will be executed. Please use break to prevent the code from automatically running to the next case.

Examples

Show today's weekday name. Please note that Sunday = 0, Monday = 1, Tuesday = 2, etc .:

var d=new Date().getDay(); 
switch (d) 
{ 
  case 0:x="今天是星期日"; 
  break; 
  case 1:x="今天是星期一"; 
  break; 
  case 2:x="今天是星期二"; 
  break; 
  case 3:x="今天是星期三"; 
  break; 
  case 4:x="今天是星期四"; 
  break; 
  case 5:x="今天是星期五"; 
  break; 
  case 6:x="今天是星期六"; 
  break; 
}

default keyword
Use the default keyword to specify what to do when a match does not exist:

var d=new Date().getDay();
switch (d)
{
    case 6:x="今天是星期六";
    break;
    case 0:x="今天是星期日";
    break;
    default:
    x="期待周末";
}
document.getElementById("demo").innerHTML=x;

My application scenario

Insert picture description here
Reference: https://www.runoob.com/js/js-switch.html

Published 252 original articles · Like 106 · Visits 30,000+

Guess you like

Origin blog.csdn.net/weixin_42554191/article/details/105460967