Could anyone explain why the trace result of the code below are "5,5,5,5,5" rather than "1,2,3,4,5" and how do you make the anonymous function refer the collect element in the array?( in this example, "var item" should be referring list[0],[1],[2],[3],[4]).
var list:Array=[1,2,3,4,5];
var funcs:Array=[];
for each(var item:int in list){
funcs.push( function(){
trace(item);
});
}
for each(var func:Function in funcs){
func();
}
trace result: 5,5,5,5,5
var helper:Function = function(i:int):Function { return function():void { trace(i); } }then change tofuncs.push( helper(item) );what it does is pass current loop value of item tot he new closure created by helper