JavaScript basic switch conditional branch statement

JavaScript basic switch conditional branch statement

1. Switch syntax:

//我们先来看一下如果用if来写一个条件语句
var a=prompt("请输入:");
//将输入的值转换为整数类型
var num=Number(a)
//如果num值等于数字1,那么浏览器页面会出现一个字符串“一”
if(num==1){
    
    
    document.write("一")
}
//如果num值等于数字2,那么浏览器页面会出现一个字符串“二”
if(num==2){
    
    
    document.write("二")
}
//如果num值等于数字3,那么浏览器页面会出现一个字符串“三”
if(num==3){
    
    
    document.write("三")
}
//把上面的if语句转换为switch...case...语句来表达就是:
var a=prompt("请输入:");
//将输入的值转换为整数类型
var num=Number(a)
	switch(num){
    
    
		case 1:
         	document.write("一")
         break;
         case 2:
         	document.write("二")
         break;
         case 3:
         	document.write("三")
         default:
         	document.write("找不到")
         break;
}
//switch...case...语句的语法结构就是:
	switch(条件表达式){
    
    
                case 表达式1:
                	执行语句
                break;

                case 表达式2:
                	执行语句
                break;

                case 表达式3:
                	执行语句
                break;

                case 表达式4:
                	执行语句
                break;
                default:    //这个相当于if语句的else
                	执行语句
                break;
            }

Two, switch execution process

  • During execution, the value of the expression after the case and the value of the expression after the switch will be compared in turn.
  • If the comparison result is true, the code will be executed from the current case, and all the code after the case will be executed. Therefore, in general, a break must be added after the execution statement after each case! ! ! , This ensures that only the statements after the current case will be executed, and the statements after other cases will not be executed.
  • If the comparison result is false, then continue to compare downward.

  • If all the comparison results are false, only the statement after default is executed.

3. Summary:

The function of the switch statement and the if statement are actually duplicated. The function of if can be realized by using switch, and the function of switch can also be realized by using if, so when we use it, we can choose according to our own habits, as if we are in the process of using There are still more if statements

Guess you like

Origin blog.csdn.net/weixin_46475440/article/details/108745843