JavaScript循环变量作用域 [英] JavaScript loop variable scope
问题描述
为什么要打印 alert()
函数 i
的值而不是返回 undefined
?
<$ p $($ i $ = $; $ i $; $ i $ = $ $ $ $ $ $ $ $ $ $ $ $ $ $
$ b alert(什么是i?+ i);
});
我对JS很新,几乎在所有其他语言中,在for循环的范围中将包含该循环的值,但在这种情况下,为什么?
即什么是'我'? 10'
被打印出来。
表达式(包括赋值表达式)或变量声明。通常用于初始化计数器变量。这个表达式可以有选择地用var关键字声明新的变量。 这些变量对于循环来说不是本地的,也就是说,它们与for循环处于相同的范围。这个表达式的结果被丢弃。
Just a quick question about the scoping of JavaScript variables.
Why does the alert()
function print the value of i
instead of returning undefined
?
$(document).ready(function () {
for(var i = 0; i < 10; i += 1){
}
alert("What is 'i'? " + i);
});
I'm fairly new to JS, and in nearly all other languages I've dabbled, a declaration in the scope of the for loop would contain the value to that said loop, but not in this case, why?
i.e. What is 'i'? 10'
is printed.
See the MDN for the "initialization parameters" of a for
-loop:
An expression (including assignment expressions) or variable declaration. Typically used to initialize a counter variable. This expression may optionally declare new variables with the var keyword. These variables are not local to the loop, i.e. they are in the same scope the for loop is in. The result of this expression is discarded.
这篇关于JavaScript循环变量作用域的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!