在 JavaScript 中,为什么当我们在范围之外打印时会打印 i
值
test();
function test(){
for(var i=0;i<10 ;i++){
console.log(i)
}
console.log('outside'+i)
}
与 Java 相比,它会给出编译错误吗?
for(int x = 10; x < 20; x = x+1) {
System.out.println("value of x : " + x );
}
System.out.print("value o " + x );
最佳答案
JavaScript 具有函数作用域而不是 block 作用域(C、C#、C++、Java 和许多其他编程语言具有 block 作用域)。在 JavaScript 中,函数内任意位置定义的变量将在函数中的任意位置可见:
function test() {
console.log(x); // logs undefined, because x is a variable that has no value yet
if (true) {
x = 42;
} else {
var x = 5; // x is not set to 5, but it is acknowledged as a variable
}
console.log(x); // logs 42 because the value in variable x has been set to 42
console.log(y); // Error because y is not declared
}
您可能会看到关于此的一件事是 var
提升。这意味着 JS 解释器的行为就像作用域(函数或全局)中的所有 var
语句都移动到该作用域的开头:
function foo() {
console.log(x,y);
var x = 4;
var y = 2;
var x = 0;
}
// is equivalent to:
function foo() {
var x,y;
console.log(x,y);
x = 4;
y = 2;
x = 0;
}
有关 MDN 的更多详细信息
另外,请注意 var
和 let
之间的区别来自 ECMAScript6
关于javascript - 为什么它打印 i 值(它已经超出了范围)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22732529/