JavaScript 切换奇怪的行为

标签 javascript function switch-statement

我有以下代码片段。

var caseObj = function () {

}

switch (typeof caseObj) {

    case "function":
        console.log("it is function");

    case "object":

        console.log("It is object now");
}

它的输出是

it is function.
It is object now.

但是 typeof caseObj 给出了输出 function 但它仍然评估 案例“对象”案例也。

这怎么可能?我做错了什么吗?

编辑:

typeof caseObj 给出了 function,所以它执行那个 case 但它也 执行 object 案例。为什么会出现这种奇怪的行为?

最佳答案

问题不在于 typeof,而是您错过了 case 中的 break 语句。这将使 casefunction OR object 并执行这两个 case 的 block 。

您错过了 break; case 的语句。这就是在下一个 case 中吵架的原因。

The break statement terminates the current loop, switch, or label statement and transfers program control to the statement following the terminated statement.

var caseObj = function() {

}

switch (typeof caseObj) {

  case "function":
    document.write("it is function");
    break;

  case "object":

    document.write("It is object now");
    break;
}

来自答案中的评论:

但是如果没有匹配的 case 并且退出 switch,它也会在不中断的情况下下降。但是它也执行 case "object": statment。为什么?

来自 MDN

If a match is found, the program executes the associated statements. If multiple cases match the provided value, the first case that matches is selected, even if the cases are not equal to each other.

The optional break statement associated with each case label ensures that the program breaks out of switch once the matched statement is executed and continues execution at the statement following switch. If break is omitted, the program continues execution at the next statement in the switch statement.

关于JavaScript 切换奇怪的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32369133/

相关文章:

javascript - 如何过滤 typescript 中的对象数组,以便只留下包含可选键的对象(并且 typescript 知道)?

php - 将 Javascript 发布到 PHP 文件?

c++ - 随机函数可以返回的范围是多少?

if-statement - keras( tensorflow 后端)使用 K.switch() 进行条件分配

java - 打印 Getter 方法

javascript - amCharts 设置条形标签图表中缺少最大 Y 轴和 X 轴值

javascript - 将 optgroup 与 knockout.js 一起使用

Python:脚本逐个字母而不是整个单词打印出字典值?

用于迭代函数定义的 JavaScript 闭包

dart - flutter 开关 - onChanged 不改变