只是一个关于 JavaScript 变量作用域的快速问题。
为什么 alert()
函数打印 i
的值而不是返回 undefined
?
$(document).ready(function () {
for(var i = 0; i < 10; i += 1){
}
alert("What is 'i'? " + i);
});
我是 JS 的新手,在我接触过的几乎所有其他语言中,for 循环范围内的声明将包含该循环的值,但在这种情况下不是,为什么?
即“我”是什么?打印 10'
。
最佳答案
有关 initialization parameters 的“for
-loop ”,请参阅 MDN :
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 循环变量作用域,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18465211/