可能重复:
Javascript closure inside loops - simple practical example
How do I pass the value (not the reference) of a JS variable to a function?
Why always the last reference to the object is used in loop?
我有一个id数组,我循环并希望在setTimeout调用的函数中使用,但是当执行下面的“func”时,它似乎只能看到存储在数组中的最后一个id。 我一直在尝试使用闭包来解决问题,但没有成功。
// loop over array an call setTimeout for loading an image
for (var i = 0; i < idlist.length; i++) {
// variable i want use in function
var lookup = idlist[i];
var func = function() {
alert(lookup); // this is always the last value in the "idlist" array
};
setTimeout(func, 500);
}