我怎么能写记得有一个改变变量的旧值一个JS回调函数? [英] How can I write a JS callback function that remembers the old value of a changing variable?

查看:195
本文介绍了我怎么能写记得有一个改变变量的旧值一个JS回调函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面是我的JS程序的简化。的 MYLIST 的是一个字符串数组和<​​EM> MyAsync 的是一个函数,它接受一个对象,并安排所提供的回调在以后的时间被调用。

Here's a simplification of my JS program. mylist is an array of strings and MyAsync is a function that takes an object and arranges for the supplied callback to be called at a later time.

for (var myindex = 0; myindex < mylist.length; myindex += 1) {      
    MyAsync(mylist[myindex], function () { alert(myindex); });
}

MYLIST 的有十个项目,结果是各出10两警报消息。好吧,这显然使用循环结束后的 myindex 的价值。所以我做一个细微的变化...

When there's ten items in mylist, the result is two alert messages each showing "10". Okay, it's clearly using the value of myindex after the loop finishes. So I make a slight change...

for (var myindex = 0; myindex < mylist.length; myindex += 1) {
    var copyindex = myindex;
    MyAsync(mylist[myindex], function () { alert(copyindex); });
}

现在,每个警报显示为9。

Now, each alert shows "9".

我如何请安排回调函数知道 myindex 的是当时的 MyAsync 的被调用?

How do I please arrange for the callback function to know what myindex was at the time MyAsync was invoked?

异步,billpg。

推荐答案

是啊,作为意见和<一个href=\"http://stackoverflow.com/questions/21510331/functions-within-loops-why-are-they-considered-an-error\">not使得你正在经历的原因循环功能。

Yeah, as the comments and not making functions in a loop for the reason you are experiencing.

我们可以用一个递归函数来代替:

We can use a recursive function instead :

 var len = mylist.length;

 function asyncLoop(index) {
    MyAsync(mylist[index], function () { 
    if(index < len) {
        asyncLoop(++index);
     }
    });
  } 
  asyncLoop(0);


注释, - 开除他们全部关闭在同一时间*(* - 快,一个循环可以运行)。和数组的跟踪计数 ...


As comments , - firing them all off at the same time* ( *- quick as a loop can run ). and keeping track of the array count ...

 function asyncDo(index) {
    MyAsync(mylist[index], function () { 
      /* we have access to the array index here */
      console.log(index);
    });
  } 

  for ( var i=0, len=mylist.length; i<len; ++i) { asyncDo(i); }

这篇关于我怎么能写记得有一个改变变量的旧值一个JS回调函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆