Ruby 的 Case 语句与 Javascript 的 Switch 语句

Ruby's Case statement vs Javascript's Switch statement

我刚刚学习了 Javascript 的 Switch 语句,并认为它的工作方式与 Ruby 的 Case 语句相同。但是它略有不同,我不明白为什么 Switch 语句会继续打印出其余的行。请参阅下面的比较示例:

    option = 2
    case option
    when 1 
      print "You selected option 1."
    when 2
      print "You selected option 2."
    when 3
      print "You selected option 3."
    when 4
      print "You selected option 4."
    end

上面Ruby中的case语句只会打印出:You selected option 2.

然而,当它翻译成Javascript的Switch语句时:

    var option = 2
    switch (option) {
      case 1:
        console.log("You selected option 1.");
      case 2:
        console.log("You selected option 2.");
      case 3:
        console.log("You selected option 3.");
      case 4:
        console.log("You selected option 4.");
    }

上面的 Switch 语句将打印

    You selected option 2.
    You selected option 3.
    You selected option 4.

我必须在 Switch 语句中的每个 case 之后放置一个 break 才能使其工作。

有人可以解释原因吗?在 Javascript 中是否有更简单的方法或方法?

Java脚本遵循 C 传统,要求显式 break 中断 switch。 C++ 和 Java 在这方面是相同的,以及(我敢肯定)无数其他 C 派生词。

要摆脱一个case:

switch (something) {
  case value:
    console.log("whatever");
    break;
  case other:
    console.log("other");
    break;
}

没有 break,执行 "falls through" 到后续的 case 块。