- The keyword switch can be followed by an expression or value in parentheses, usually a variable
- The keyword case, followed by the expression or value of an option, followed by a colon
- The value of the switch expression is compared to the value of the case in the structure
- If there is a matching congruence (===), the code block associated with the case is executed and stops when a break is encountered, terminating the entire switch statement code execution
- If all case values do not match the expression values, execute the code in default
The value in case is a judgment, which matches true in switch
<script>
let score = prompt('Input score')
score = parseFloat(score)
switch (true) {
case score >= 90:
alert('A');
break;
case score >= 80:
alert('B');
break;
default:
alert('C');
}
</script>
Copy the code
Case is a value that matches the variable in the switch
<script>
// The prompt input box will pop up, asking the user to enter the fruit name, take the value and save it in the variable.
// use this variable as the expression inside the switch parentheses.
// use several different fruit names after case. Be sure to enclose them in quotes, as they must be congruent matches.
// Pop up different prices. Also note that a break is added after each case to exit the switch statement.
// Set default to no such fruit.
var fruit = prompt('Please enter the fruit of enquiry :');
switch (fruit) {
case 'apple':
alert('The price of apples is 3.5 per catty');
break;
case 'durian':
alert('The price of durian is 35 per catty');
break;
default:
alert('No such fruit');
}
</script>
Copy the code