setTimeout only sees last value in array? [duplicate]

女生的网名这么多〃 提交于 2019-12-24 12:17:38

问题


Possible Duplicate:
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?

I have an array of ids which I loop over and want to use in a function called by setTimeout, however when "func" below is executed it only seems to see the last id stored in the array. I have been trying to uses closures to fix the issue but have had no success.

  // 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);
}

来源:https://stackoverflow.com/questions/7399411/settimeout-only-sees-last-value-in-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!