Home > Web Front-end > JS Tutorial > A brief introduction to the switch statement in JavaScript (with code)

A brief introduction to the switch statement in JavaScript (with code)

不言
Release: 2018-09-28 15:45:11
forward
3021 people have browsed it

This article brings you a brief introduction to the switch statement in JavaScript (with code). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

JavaScriptswitch statement

The switch statement is used to perform different actions based on different conditions.

JavaScript switch statement

Use the switch statement to make multiple selections.

Syntax:

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

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 executing statement. default Default is selected by default when there is no matching option.

Example:

<!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>
Copy after login

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

The above is the detailed content of A brief introduction to the switch statement in JavaScript (with code). For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:cnblogs.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template