the code
function switchF() {
let key = 5;
switch (key) {
case 1, 2, 3, 4, 5:
console.log('工作日');
break;
case 6, 7:
console.log('休息日');
break;
default:
console.log('输入有误');
break;
}
}
switch
MDN
switch
A statement evaluates an expression , matches the expression's value to a clause, and executes the statementcase
associated with that case .switch (expression) { case value1: // 当 expression 的结果与 value1 匹配时,执行此处语句 break; case value2: // 当 expression 的结果与 value2 匹配时,执行此处语句 break; ... case valueN: // 当 expression 的结果与 valueN 匹配时,执行此处语句 break; default: // 如果 expression 与上面的 value 值都不匹配,执行此处语句 break; }
expression
Ancase
expression used to match substatements.
case valueN
optional The clause to use for
matching . If a match is given , the statements in this clause are executed until the end of the statement or one is encountered . optional A clause; if given, this clause will be executed if the value of does not match any of the statements. A statement first evaluates its . It will then start from the first clause until it finds a clause whose expression value is equal to the value entered (using the strict operator (en-US), ===) and transfers control to Given this clause, the associated statement is executed. (If more than one match the supplied value, the first one that matches is chosen , even if these are not equal to each other.) If no clause matches, the program looks for that optional clause, and if found, it will Control is handed over to it, and the relevant statement is executed. If there is no clause, the program will continue to execute to the end. By convention, the clause is the last clause, but it doesn't need to be. The optional break statement ensures that the program immediately breaks out of the associated clause and continues executing the following statement. likeexpression
case
expression
valueN
case
switch
break
default
default
expression
case
switch
expression
case
expression
case
case
case
case
default
default
switch
default
case
switch
switch
break
is omitted, program execution continues withswitch
the next statement in the statement.
break
MDN
break
statement terminates the current loop, switch statement, or label statement and transfers program control flow to the statement immediately following the terminated statement.
break [label];
wherelabel
is the identifier associated with the statement label. Required ifbreak
the statement is not inside a loop or switch statement.
break
Statements contain an optional label that allows programs to escape a labeled statement.break
Statements need to be embedded in quoted tags. The marked statement can be any block statement; not necessarily a loop statement.
break
The statement cannotfunction
be used directly in the function body, and the statement should be nested in the current loop or statementbreak
to be interrupted .switch
label
for (let i = 0; i < 9; i++) { if (i === 7) break; console.log(i); }