关于功能:JavaScript切换奇怪的行为

JavaScript switch strange behavior

我有以下代码片段。

1
2
3
4
5
6
7
8
9
10
11
12
13
var caseObj = function () {

}

switch (typeof caseObj) {

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

    case"object":

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

它的输出是

1
2
it is function.
It is object now.

但是,typeof caseObj给出了function的输出,但它仍在评估案例"对象"案例。

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

编辑:

typeof caseObj给了function,所以它执行了这个案子,但它也执行object案件。为什么会有这种奇怪的行为?


问题不在typeof上,但您在本例中遗漏了break语句。这将使casefunction OR object一样,并执行这两个案件的封锁。

你错过了caseS的break;声明,这就是下一个case退出的原因。

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
var caseObj = function() {

}

switch (typeof caseObj) {

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

  case"object":

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

根据答案中的评论:

但是如果没有匹配的案例和退出开关,它也会掉下来,但是它执行案例"对象":语句,为什么?

从多点传送

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.


switch执行从与请求值匹配的第一个case开始,从顶部开始。

然后,除非在某个地方使用break,否则它将继续执行所有case,从第一个匹配到底部。

例如,如果您在示例中反转2个case,它将只输出"it is function"。


在每个case子句的结尾没有break语句。当您这样做时,控制流将传递到下一个case子句的语句,不管case条件是否满足。例如,如果您有:

1
2
3
4
5
6
7
var x = 1;
switch(x) {
   case 0: console.log(0);
   case 1: console.log(1);
   case 2: console.log(2);
   case 3: console.log(2);
}

输出将是:

1
2
3
1
2
3

但如果你在每件案子中都有突破

1
2
3
4
5
6
7
var x = 1;
switch(x) {
   case 0: console.log(0);break;
   case 1: console.log(1);break;
   case 2: console.log(2);break;
   case 3: console.log(2);break;
}

输出只有1