JavaScript切换奇怪的行为 [英] JavaScript switch strange behavior
问题描述
var caseObj = function(){
}
switch(typeof caseObj){
casefunction:
console.log(it is function);
caseobject:
console.log(It is object now);
}
它的输出是
它是函数。
现在是对象。
但是 typeof caseObj
给出的输出 function
但它仍然会评估
caseobject情况。 有可能吗?我做错了anythig?
编辑:
typeof caseObj
给出函数
,所以它执行这个例子,但它也是
执行 object
case.Why这个奇怪的行为?
问题不在于 typeof
,但您已经错过了案例中的 break
语句。这将使函数OR对象
,并执行这两个块个案。
您错过了 break;
对于情况
s的情况。这是在下一个情况
中出现的原因。
语句终止当前循环,切换或标签语句,并将程序控制转移到语句后面的语句。
var caseObj = function(){} switch(typeof caseObj){casefunction:document.write(it is function);打破; caseobject:document.write(现在是对象); break;}
但是如果没有匹配大小写并退出switch,它也会崩溃。但它执行caseobject:statment。为什么?
From MDN
如果找到匹配项,程序将执行相关的语句。如果多个案例匹配提供的值,即使案例不相等,也会选择匹配的第一个案例。
与每个案例相关的可选break语句标签确保一旦执行匹配的语句,程序便跳出切换,并在切换后的语句中继续执行。如果省略break,程序将继续执行switch语句中的下一个语句。
I have following code snippets.
var caseObj = function () {
}
switch (typeof caseObj) {
case "function":
console.log("it is function");
case "object":
console.log("It is object now");
}
Its output is
it is function.
It is object now.
But typeof caseObj
gives output function
but it still evalutes
case "object" case also.
How it is possible? Am I doing wrong anythig?
EDIT :
typeof caseObj
is giving function
,So it executing that case but it also
executing object
case.Why this strange behavior?
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.
You missed the break;
statement for the case
s. This is the reason, of falling out in the next 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;
}
From the comments in the answer:
But without break it also fall-down if there is not matching case and exit from switch.But it executing case "object": statment as well.Why?
From 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切换奇怪的行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!