0

Please see the code below:

var l = [1,2,3,4]
var l2 = []
for (var i =0;i< l.length;i++) {
    l2.push( function () {alert(l[i])}   )
}


l2[0]()

what I expect is l2[0] will alert "1". But this is not working as I expected. It seems that the value of l is not read in the for-loop. And for my case, I do not want to pass any variables into the anonymous function. Is it possible to solve this?

hengyue li
  • 448
  • 3
  • 17

0 Answers0