Java 与 JavaScript 变量作用域 [英] Java vs. JavaScript variable scope

查看:57
本文介绍了Java 与 JavaScript 变量作用域的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在以下 Java 代码段中,i 的范围仅限于 for 循环的内部.这就是它导致错误的原因.然而,在类似的 JS 代码段中,i 显然可以在循环之外访问.这怎么可能?

In the following Java snippet, the scope of i is limited to the inside of the for loop. That's why it causes an error. However, in the similar JS snippet, the i is apparently accessible outside of the loop. How is that possible?

Java:

for(int i=0;i<10;i++) {
    ...
}
System.out.println(i);

输出:我没有定义"

JS:

for(var i=0;i<10;i++) { 
    ...
}
console.log(i);

输出:10

我没想到会看到 JS 的输出.我想知道 JS 与 Java 有何不同.JavaScript 变量范围是如何工作的?

I didn't expect to see output from the JS. I want to know how JS differs from Java. How does JavaScript variable scope work?

推荐答案

在 Javascript 中,局部"变量具有函数作用域,而不是块作用域.

In Javascript "local" variables have function scope, not block scope.

所有局部变量声明都被提升"到当前作用域的顶部,所以你的代码等价于:

All local variable declarations are "hoisted" to the top of the current scope, so your code is equivalent to:

var i;
for (i = 0; i < 10; ++i) {
}
console.log(i);

请注意,虽然声明被提升,但任何赋值都不会.例如这段代码

Note that while the declaration is hoisted, any assignment is not. e.g. this code

function test() {
    console.log(i);  // undefined
    var i = 1;       // declaration and assignment
    console.log(i);  // 1
}

相当于:

function test() {
    var i;           // declaration hoisted
    console.log(i);  // undefined
    i = 1;           // assignment still happens here
    console.log(i);  // 1
}

这篇关于Java 与 JavaScript 变量作用域的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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