#JavaScript
#JavaScript / conditional statement / switch
The most basic conditional statement is the if. However, the disadvantage is that if there are many values to compare in the conditional expression, the code becomes longer and less readable. In such cases, it is recommended to use switch.
grammar
switch ( condition ) {
case value1:
statement1;
break;
case value2:
statement2;
break;
...
default:
statement3;
}
If the value of condition is value1, then statement1 is executed, if value2 is statement2, otherwise default is applied and statement3 is executed.
Compare values in order, and if there is a break when the conditions are met, no further comparisons will be made. In other words, immediately exit the switch construct. If there is no break, continue with the next comparison even if the condition is met.
example
This example outputs "First" if you enter 1, "Second" if you enter 2, "Third" if you enter 3, and "You did not input 1 or 2 or 3." if you enter any other value. .
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>JavaScript Statement | switch</title>
<script>
var jb = prompt( 'Enter 1 or 2 or 3', '' );
switch ( jb ) {
case '1':
var jb1 = 'First';
break;
case '2':
var jb1 = 'Second';
break;
case '3':
var jb1 = 'Third';
break;
default:
var jb1 = 'You did not input 1 or 2 or 3.';
}
</script>
</head>
<body>
<script>
document.write( '<p>' + jb1 + '</p>' );
</script>
</body>
</html>
result
'Javascript' 카테고리의 다른 글
[JavaScript] Declare and call javascript/function/function (0) | 2022.08.02 |
---|---|
[JavaScript] JavaScript / Repeat Statements / while, do - while, for (0) | 2022.08.01 |
[JavaScript] JavaScript / Conditionals / if, else if, else (0) | 2022.08.01 |
[JavaScript] JavaScript/operator/typeof operator (0) | 2022.08.01 |
[Javascript] JavaScript / operator / comparison operator (0) | 2022.07.29 |