Why can't I roll a loop in Javascript?

…衆ロ難τιáo~ 提交于 2019-12-03 07:41:25

this is a common problem when dealing with closures. try this:

for (var i = 0; i < 6; i++) {
    (function(i){
      dojo.connect(dijit.byId("project" + i).InputNode, "onChange",  function()   {makeMatch(i);});
    }(i));
}

i is a local variable inside the for loop. When the onChange function is called, all 6 functions have a reference to i, which is 6.

It's the same problem as #4 on Jon Skeet's C# Brainteaser's page

List<Printer> printers = new List<Printer>();
for (int i=0; i < 10; i++)
{
    printers.Add(delegate { Console.WriteLine(i); });
}

foreach (Printer printer in printers)
{
    printer();
}

which prints all 10's

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!