为什么for循环计数器在javascript中退出循环后不会被破坏?

问题描述:

for(var i=0;i<5;i++){}
alert(i);

在javascript中这将获得5
其他语言,如C ++,java,c#.. ..只会给出一个错误,即i变量没有在上下文中定义。

in javascript this will get us 5 other languages like C++, java, c# .... will simply give an error that the i variable isn't defined in the context.

那么为什么for循环计数器在退出循环之后不会被破坏javascript?

So why the for loop counter doesn't get destroyed after exiting the loop in javascript?

这是因为JavaScript引擎会将变量decalaration移动(提升)到函数顶部在函数 1 中声明它的位置。 JavaScript没有块范围。

This is because the JavaScript engine will move ("hoist") the variable decalaration to the top of the function no matter where it is declared inside the function1. JavaScript does not have block scope.

{
//Some code
    for(var i=0;i<5;i++){}
    alert(i);
//Some code
}

相当于:

{
  var i;
 //.. some code
 for(i=0;i<5;i++){}
    alert(i);
}

1 除非是使用 catch 子句捕获的异常;该变量的范围是 catch block。

1 Unless it's the exception being caught with a catch clause; that variable is scoped to catch block.

用于定义块范围变量 ecmascript 6 specs (javascript 1.7)介绍 即可。目前,这只适用于最新版本的FireFox浏览器并处于共识阶段。

For defining block scope variables ecmascript 6 specs (javascript 1.7) introduces let. Currently this will work only in latest version of FireFox browser and in consensus stage.

<script type="application/javascript;version=1.7">
     //Some code

        for (let i = 0; i < 10; i++) {

            alert(i); // 1, 2, 3, 4 ... 9
        }

        alert(i); // Here you will get an error here saying ReferenceError: i is not defined.
    }
</script>

小提琴

Fiddle