Home  >  Article  >  Web Front-end  >  Introduction to the usage of switch statement in JavaScript learning

Introduction to the usage of switch statement in JavaScript learning

青灯夜游
青灯夜游forward
2018-10-16 17:23:232638browse

This article will give you an introduction to the use of switch statements in JavaScript learning. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

Let’s first learn about the JavaScript switch statement

Use the switch statement to make multiple selections.

Syntax:

switch( 变量1 ){
  case 变量2:
      //语句1;
    break;
    case 变量3:
         //语句2;
    break;
    default:
           //语句3;
  }

Execution principle: The value of variable 1 is compared with the value of case. For example, if variable 1 is equal to case variable 2, statement 1 will be executed. If variable 1 is equal to case variable 3, execute statement 2. If neither match, execute statement 3.

break ends the currently executed statement. default Default is selected by default when there is no matching option.

Code example description:

<!DOCTYPE html>
<html>

	<head>
		<meta charset="UTF-8">
		<title>Insert title here</title>
	</head>

	<body></body>
	<script type="text/javascript">
		var num = 3;
		switch(num) {
			case 0:
				alert("0");
				break;
			case 1:
				alert("1");
				break;
			case 2:
				alert("2");
				break;
			case 3:
				alert("3");
				break;
			case 4:
				alert("4");
				break;
			default:
				alert("默认选项");
				break;
		}
		 //当num等于0,执行alert("0");......如果都不匹配,就执行alert("默认选项");
	</script>

</html>

default keyword When all options do not match, the code of the default option is executed by default.

Summary: The above is the entire content of this article, I hope it will be helpful to everyone's study. For more related tutorials, please visit JavaScript Video Tutorial, jQuery Video Tutorial, bootstrap Tutorial!

The above is the detailed content of Introduction to the usage of switch statement in JavaScript learning. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:cnblogs.com. If there is any infringement, please contact admin@php.cn delete