Javascript 中无中断切换

pra*_*abh 1 javascript switch-statement

drink = 'beer'

switch(drink){
    case 'beer':
    case 'whiskey':
        console.log('The drink is BEER or WHISKEY');
    case 'juice':
        console.log('The drink is JUICE');
    default:
        console.log('Nothing to drink');
}
Run Code Online (Sandbox Code Playgroud)

对于上面的代码,为什么我会在控制台中收到所有三个消息?有人可以解释一下吗?如果没有break,我期望打印案例消息和默认消息,但为什么“juice”相关消息也出现在控制台中?

小智 6

根据switch 语句参考,“如果您忘记了中断,那么脚本将从满足条件的情况开始运行,并且无论是否满足条件都将运行之后的情况”。因此,在switch语句内部,一旦case语句与给定变量匹配,将忽略条件执行所有后续语句,直到break遇到语句或右大括号。

如果您将代码重写为此,输出将仅为“饮料是啤酒或威士忌”和“没有什么可喝的”。

drink = 'beer'

switch(drink){
    case 'juice':
        console.log('The drink is JUICE');
    case 'beer':
    case 'whiskey':
        console.log('The drink is BEER or WHISKEY');
    default:
        console.log('Nothing to drink');
}
Run Code Online (Sandbox Code Playgroud)