Closures in a for loop and lexical environment

后端 未结 4 1225
青春惊慌失措
青春惊慌失措 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:46

    Since the variable i is declared outside the scope of the loop, it retains its final value after the loop has completed. The anonymous functions you're creating then all bind to this variable, and when they're called, they all get the same final value of N.

    There's a good discussion of this in this question.

提交回复
热议问题