Javascript 为什么打印i值(它已经超出范围)?
在JavaScript中,为什么在范围外打印时打印Javascript 为什么打印i值(它已经超出范围)?,javascript,jquery,Javascript,Jquery,在JavaScript中,为什么在范围外打印时打印i值 test(); function test(){ for(var i=0;i<10 ;i++){ console.log(i) } console.log('outside'+i) } test(); 功能测试(){ 对于(var i=0;i在这种情况下,i的作用域不是for循环,而是test()函数。在这种情况下,i的作用域不是for循环,而是test()函数。代码>与ECMACRISPT
i
值
test();
function test(){
for(var i=0;i<10 ;i++){
console.log(i)
}
console.log('outside'+i)
}
test();
功能测试(){
对于(var i=0;i在这种情况下,i
的作用域不是for
循环,而是test()
函数。在这种情况下,i
的作用域不是for
循环,而是test()
函数。
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;
}
更多详情
<>也注意到 var >代码>与ECMACRISPT6/P>> P>JavaScript的功能范围不是块范围(C、C、C、C++和java等许多编程语言都有块范围)。在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;
}
更多详情
另外,请注意var
与ECMAScript6之间的区别,这意味着它在javascriptYes中使用整个函数,如果使用了一个变量但没有在本地声明,那么它在作用域中变为全局。这意味着它在javascriptYes中使用整个函数,如果使用了一个变量但没有在本地声明,那么它在作用域中变为全局在JavaScriptjavascript中使用分号是一种很好的做法JavaScript只使用函数作用域,而不是块作用域。此外,在JavaScriptjavascript中使用分号也是一种很好的做法JavaScript@A.Wolff我想你弄错了。bar()
->引用错误,而baz();var baz=function(){};
->TypeError。第一个表示没有像bar这样的东西,而第二个表示您正在调用无法调用的东西(未定义)。好吧,我的错,我明白您的意思了;)@A.Wolff我想您弄错了。bar()
->引用错误,而baz();var baz=function(){};
->TypeError。第一个表示没有像bar这样的东西,而第二个表示您正在调用无法调用的东西(未定义)。好吧,我的错,我明白您的意思了;)