如何在内联函数中访问该变量?
这是我的困境。
我有这一段代码:
var list_of_numbers = new Array();
function AddToArray(func)
{
// Add to the *beginning* of the array
// essentially reversing the order
list_of_numbers.unshift(func);
}
function DisplayNumber(num)
{
document.write(num);
}
for(var i=0;i<5;++i)
{
AddToArray(function() { DisplayNumber(i); });
}
for(var i=0;i<5;++i)
{
list_of_numbers[i]();
}
应该发生的情况是,5 个内联函数将被添加到数组中 - 每个获取 i
的副本。然而这并没有发生。
预期输出:
43210
实际输出:
01234
Here is my dilemma.
I've got this section of code:
var list_of_numbers = new Array();
function AddToArray(func)
{
// Add to the *beginning* of the array
// essentially reversing the order
list_of_numbers.unshift(func);
}
function DisplayNumber(num)
{
document.write(num);
}
for(var i=0;i<5;++i)
{
AddToArray(function() { DisplayNumber(i); });
}
for(var i=0;i<5;++i)
{
list_of_numbers[i]();
}
What is supposed to happen is that 5 inline functions will be added to the array - each taking a copy of i
. However this does not happen.
Expected output:
43210
Actual output:
01234
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您有两个独立的问题,都与范围有关。
您传递给
AddToArray
的匿名函数绑定到变量i
,而不是当前值。为了解决这个问题,我们创建一个新函数,并传入当前的i
。JavaScript 具有函数作用域,因此当您在第二个循环中重新声明
i
时,您仍然在修改同一个变量。因此,我们将其重命名为j
。如果只有第一个是问题,您将得到 55555,因为所有函数都将使用相同的
i
,此时为 5。但是,由于您对第二个函数重用了i
index,i
设置为当前循环索引。You have two separate issues, both related to scope.
The anonymous function you're passing to
AddToArray
is bound to the variablei
, not the current value. To address this, we create a new function, and pass in the currenti
.JavaScript has function scope, so when you re-declare
i
in the second loop, you're still modifying the same variable. Thus, we rename it toj
.If only the first were an issue, you would get 55555, since all functions would use the same
i
, at that point 5. However, since you reusei
for the second index,i
is set to the current loop index.