这是我的 JS 程序的简化。 mylist 是一个字符串数组,MyAsync 是一个函数,它接受一个对象并安排稍后调用所提供的回调。
for (var myindex = 0; myindex < mylist.length; myindex += 1) {
MyAsync(mylist[myindex], function () { alert(myindex); });
}
当mylist中有十个项目时,结果是两条警报消息,每条都显示“10”。好的,很明显,循环结束后使用的是 myindex 的值。所以我做了一些小小的改变......
for (var myindex = 0; myindex < mylist.length; myindex += 1) {
var copyindex = myindex;
MyAsync(mylist[myindex], function () { alert(copyindex); });
}
现在,每个警报都显示“9”。
我如何安排回调函数来了解调用 MyAsync 时 myindex 是什么?
异步,bilpg。
最佳答案
是的,正如评论和not making functions in a loop因为您正在经历的原因。
我们可以使用递归函数来代替:
var len = mylist.length;
function asyncLoop(index) {
MyAsync(mylist[index], function () {
if(index < len) {
asyncLoop(++index);
}
});
}
asyncLoop(0);
<小时/>
作为注释,- 同时将它们全部关闭*(*- 像循环一样快运行)。并跟踪数组计数 ...
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); }
关于javascript - 如何编写一个 JS 回调函数来记住变化变量的旧值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22845270/