switch / case语句中的JavaScript变量范围是什么? [英] What is the JavaScript variable scope in a switch / case statement?
问题描述
在使用ASP.NET MVC创建JavaScript时,我注意到了几个范围警告,并意识到我在切换/ case语句中理解变量范围时遗漏了一些东西。
While creating JavaScript with ASP.NET MVC I noticed several scope warnings and realized that I am missing something with understanding the variable scope inside the switch / case statement.
警告:'i'已定义引用案例b和案例c
Warning: 'i' is already defined referring to case b and case c
我的代码与此类似:
switch(element) {
case 'a':
for(var i=0; i < count; i++){
do something
}
break;
case 'b':
for(var i=0; i < count; i++){
do something
}
break;
case 'c':
for(var i=0; i < count; i++){
do something
}
break;
}
我认为范围以每个break语句结束,但似乎范围没有结束直到开关/外壳结束。是整个开关/案例的范围吗?
I thought scope ended with each break statement but it seems that scope does not end until the end of the switch/case. Is scope for the entire switch/case?
推荐答案
Javascript不使用块范围。
Javascript does not use block scope.
因此,所有局部变量都在声明它们的整个函数的范围内。
Therefore, all local variables are in scope throughout the entire function in which they were declared.
但是,在您的特定情况下,没有C类似语言(我知道),其中每个 case
语句形成一个独立的范围。
例如,以下C#代码将无法编译:
However, in your particular case, there is no C-like language (that I know of) in which each case
statement forms an independent scope.
For example, the following C# code will not compile:
switch(someVar) {
case 1:
int a;
break;
case 2:
int a; //'a' is already defined
break;
}
这篇关于switch / case语句中的JavaScript变量范围是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!