Switch 语句
Switch 语句将表达式的值与 1 个或多个值进行比较,并根据该比较执行不同的代码段。
var value = 1;
switch (value) {
case 1:
console.log('I will always run');
break;
case 2:
console.log('I will never run');
break;
}
break
语句从 switch 语句中中断并确保不再执行 switch 语句中的代码。这就是如何定义部分并允许用户进行中断的情况。
警告 :每个案例缺少
break
或return
声明意味着程序将继续评估下一个案例,即使案例标准未得到满足!
switch (value) {
case 1:
console.log('I will only run if value === 1');
// Here, the code "falls through" and will run the code under case 2
case 2:
console.log('I will run if value === 1 or value === 2');
break;
case 3:
console.log('I will only run if value === 3');
break;
}
最后一个案例是 default
情况。如果没有其他匹配,这个将运行。
var animal = 'Lion';
switch (animal) {
case 'Dog':
console.log('I will not run since animal !== "Dog"');
break;
case 'Cat':
console.log('I will not run since animal !== "Cat"');
break;
default:
console.log('I will run since animal does not match any other case');
}
应该注意,案例表达可以是任何类型的表达。这意味着你可以使用比较,函数调用等作为案例值。
function john() {
return 'John';
}
function jacob() {
return 'Jacob';
}
switch (name) {
case john(): // Compare name with the return value of john() (name == "John")
console.log('I will run if name === "John"');
break;
case 'Ja' + 'ne': // Concatenate the strings together then compare (name == "Jane")
console.log('I will run if name === "Jane"');
break;
case john() + ' ' + jacob() + ' Jingleheimer Schmidt':
console.log('His name is equal to name too!');
break;
}
case 的多重包容性标准
由于 case 在没有 break
或 return
语句的情况下掉头,你可以使用它来创建多个包含标准:
var x = "c"
switch (x) {
case "a":
case "b":
case "c":
console.log("Either a, b, or c was selected.");
break;
case "d":
console.log("Only d was selected.");
break;
default:
console.log("No case was matched.");
break; // precautionary break if case order changes
}