Closures in a for loop and lexical environment

后端 未结 4 1223
青春惊慌失措
青春惊慌失措 2020-12-01 23:33

Simple case: I want to load several images which have a common name and a suffix, e.g: image0.png, image1.png, image2.png ... imageN.png

I\'m using a simple for loop

4条回答
  •  孤城傲影
    2020-12-01 23:41

    You can wrap it in a closure to avoid to use i variable, which is a loop variable and thus changes:

    (function(j) {
      images[i].onload = function () {
          console.log("Image " + i + ", " + j + " loaded");
      };
    })(i);
    

    This demonstrates the difference between i, which is a loop variable and changes, and j, which is a function-bound parameter, which doesn't change.

    See the jsfiddle here:

    • http://jsfiddle.net/VuLTa/

提交回复
热议问题