如何从for循环中的匿名函数获取当前循环迭代? [英] How to get current loop iteration from anonymous function within the for loop?
本文介绍了如何从for循环中的匿名函数获取当前循环迭代?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
<我有一个带有匿名函数的for循环,在函数中我想访问当前的循环迭代。但由于某些原因而不是循环迭代,我得到4.唯一的另一个地方4是一个值是myArray.length。如果我将i作为参数传递,我会得到[object Object]。我究竟做错了什么?我的代码:
I have a for loop with an anonymous function inside, and in the function I want to access the current loop iteration. But for some reason instead of the loop iteration, I'm getting 4. The only other place 4 is a value is myArray.length. If I pass i as an argument, I get [object Object] out. What am I doing wrong? My code:
var width = function(){
for(var i = 0, len = myArray.length; i < len; ++i){
alert(i) //this outputs the current iteration
myArray[i].load(function(){
alert(i) //this outputs 4 (or [object Object])
});
};
};
谢谢。
推荐答案
传递给 .load
的匿名函数正在循环完成后执行。
Your anonymous function passed to .load
is being executed way after your loop has finished.
您必须创建一个本地范围,并复制 i
变量:
You have to create a local scope, and copy the i
variable:
var width = function(){
for(var i = 0, len = myArray.length; i < len; ++i){
(function(i){
myArray[i].load(function(){
alert(i) //this outputs 4 (or [object Object])
});
})(i);
};
};
这篇关于如何从for循环中的匿名函数获取当前循环迭代?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文