除了 if 语句之外,JavaScript 还有 switch 语句,用来有条件地执行逻辑。当需要把同一个变量与多个可能值进行比较时,就会用到它。比较通过检查严格相等(===)完成,详见比较。对于某个变量 x,JavaScript 中 switch 语句的语法如下。
switch (x) {
case option1:
// code that is executed when "x === option1" is true
break;
case option2:
// code that is executed when "x === option2" is true
break;
default:
// code that is executed when x does not equal any of the
// options
}
default 分支是可选的,当你希望在没有任何其他选项匹配该变量时执行一些代码,就可以使用它。
上面的 break 语句是必需的,因为 JavaScript 默认会让所有分支都“贯穿”。也就是说,如果没有任何 break 语句,那么即使 x 并不匹配,第一个匹配的选项之下的所有分支里的代码也会被执行。这种“默认贯穿”的行为是在 JavaScript 中使用 switch 时常见的坑。在函数内部,也可以用 return 代替 break 来避免这个问题。
当你想对多个分支应用同一段代码时,也可以利用这种贯穿行为。在 MDN 文档 中可以找到这样一个例子。
默认情况下,不同 case 分支中的变量共享同一个作用域。这可能会导致意料之外的行为。例如,由于复制粘贴某个分支,你可能在两个分支里都声明了 let message,从而引发错误,详见 MDN 文档。为了避免共享作用域带来的问题,你可以为每个 case 分支加上一对大括号,把它的代码包成独立的代码块,从而为每个分支创建单独的作用域。
switch (x) {
case option1: {
// Variables declared here are contained to this case.
break;
}
case option2: {
// ...
break;
}
default: {
// ...
}
}
除了变量 x,你也可以使用表达式。表达式会在 switch 语句开始时求值一次,然后把结果与各个分支进行比较。一种常见的用法是“类型分支”,根据变量的类型执行不同的代码。
switch (typeof x) {
case 'string':
// code that is executed when x is a string
break;
case 'number':
// code that is executed when x is a number
break;
default:
// code that is executed when x has some other type
}
各个选项也可以是表达式。