【问题标题】:How to access this variable in an inline function?如何在内联函数中访问此变量?
【发布时间】:2010-09-04 06:09:19
【问题描述】:

这是我的困境。

我有这段代码:

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

【问题讨论】:

  • @Michael:我不明白你在说什么。
  • @Michael:我知道——这就是它应该做的。问题是它没有在循环的每次迭代中保存i 的值......我认为。
  • 是的,JavaScript 不会“保存”值。你有Closure Loop Problem

标签: javascript copy inline-functions


【解决方案1】:

您有两个独立的问题,都与范围有关。

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) 
{ 
    (function(i) 
     { 
         AddToArray(function(){ DisplayNumber(i); });
     })(i); 
} 

for(var j=0;j<5;++j) 
{ 
    list_of_numbers[j](); 
}​
  1. 您传递给AddToArray 的匿名函数绑定到变量i,而不是当前值。为了解决这个问题,我们创建了一个新函数,并传入当前的i

  2. JavaScript 具有函数作用域,因此当您在第二个循环中重新声明 i 时,您仍在修改同一个变量。因此,我们将其重命名为j

如果只有第一个是问题,您会得到 55555,因为所有函数都将使用相同的 i,此时 5。但是,由于您将 i 重复用于第二个索引,因此设置了 i到当前循环索引。

【讨论】:

  • 啊啊啊。我知道了。 AddToArray 块的语法很奇怪!感谢您的帮助。
猜你喜欢
  • 2016-06-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-12-02
  • 1970-01-01
  • 2014-04-08
  • 1970-01-01
  • 2017-06-01
相关资源
最近更新 更多