为什么for循环计数器在javascript中退出循环后不会被破坏? [英] Why the for loop counter doesn't get destroyed after exiting the loop in javascript?

查看:72
本文介绍了为什么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

这篇关于为什么for循环计数器在javascript中退出循环后不会被破坏?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆