我有以下代码片段。
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
语句。这将使 case
像 function 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/