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. |
但是,
怎么可能?我做错什么了吗?
编辑:
问题不在
你错过了
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.
然后,除非在某个地方使用
例如,如果您在示例中反转2个
在每个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