JavaScript 谜题:作用域 [英] JavaScript Puzzle: Scope
问题描述
所以我想弄清楚这个难题:
So I am trying to figure out this puzzle:
function fun1(){
var result = [];
for (var i = 0; i < 5; i++){
result.push( function() {return i} );
}
return result;
}
console.log(fun1()[0]()) // returns 5?
那个数组的第一个元素不应该返回一个返回'0'的函数吗?
Shouldn't the first element of that array return a function that returns '0'?
推荐答案
让我们一步一步分解发生的事情:
Let's break down what happens step by step:
我们声明了一个函数
fun1()
,它返回一个数组result
.
for
循环迭代 5 次,每次迭代递增 i
.
The for
loop iterates 5 times, with each iteration incrementing i
.
请注意,返回 i
的匿名函数在整个执行过程中未调用.
Notice that the anonymous function returning i
is not invoked throughout the execution.
for
循环以 i
的值为 5
结束.
The for
loop ends with the value of i
being 5
.
调用 fun1()[0]
返回一个数组 result[]
,该数组有一个函数将 reference 存储到 i
,不是 i
的 value.
Invoking fun1()[0]
returns an array result[]
which has a function that stores the reference to i
, not the value of i
.
然后调用匿名函数跟随该引用并返回i
的值,即5
.
Invoking the anonymous function then follows that reference and returns the value of i
, which is 5
.
这篇关于JavaScript 谜题:作用域的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!