可能重复:
Javascript closure inside loops - simple practical example如何从for循环中的匿名函数获取当前循环迭代?
我有一个与内部的匿名函数循环,并且在功能我想访问本次循环。但由于某种原因而不是循环迭代,我得到了4.唯一的其他地方4是一个值是myArray.length。如果我通过我作为参数,我得到[object Object]。我究竟做错了什么?我的代码:
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])
});
};
};
感谢。