本文介绍了JavaScript 开关奇怪的行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码片段.

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 但它仍然评估case "object" 也是case.

But typeof caseObj gives output function but it still evalutescase "object" case also.

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

How it is possible? Am I doing wrong anythig?

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

typeof caseObj is giving function,So it executing that case but it also executing object case.Why this strange behavior?

推荐答案

问题不在于typeof,而是你错过了案例中的break语句.这将使 casefunction OR object 并执行这两种情况的块.

The problem is not with the typeof, but you've missed the break statement in the case. That'll make the case like function OR object and execute the block of both the cases.

您错过了 break;case 语句.这就是在下一个case中失败的原因.

You missed the break; statement for the cases. This is the reason, of falling out in the next case.

break 语句终止当前循环、switch 或标号语句,并将程序控制转移到终止语句之后的语句.

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,它也会崩溃.但是它也会执行caseobject":语句.为什么?

来自 MDN

如果找到匹配项,程序将执行相关的语句.如果多个案例与提供的值匹配,则选择第一个匹配的案例,即使案例彼此不相等.

与每个 case 标签关联的可选 break 语句确保程序在执行匹配的语句后跳出 switch,并在 switch 后面的语句处继续执行.如果省略了break,程序将继续执行switch语句中的下一条语句.

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 开关奇怪的行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-18 09:49