I've been programming some stuff in ActionScript (Haxe) and arrived this very specific problem.
Here's the code (pseudo :S):
var func:Array = new Array(256);
(A) var i:Int = 0;
for(;i<256;i++) { // OR // for(i in 0...256) {
func[i] = function() { trace(i); }
}
func[0]();
func[127]();
func[256]();
The above code outputs (a):
25开发者_运维技巧6
256
256
I want that to be (b):
0
127
256
That doesn't happen, because ActionScript/Haxe is assigning the reference of i to the function, and since i equals 256 at the end of the loop where the functions get evaluated, that's why I get (a).
Does anyone know of a way to avoid that and get the expected results at (b) ?
Thanks to all of you guys and your responses.
I think I've found the answer. If you remove the line marked with (A) it works, if you leave it it doesn't. I'm pretty sure you could all figure out why that happens. Thanks again!
it's not neccessary to use callback, this should work as expected (haxe creates a local var in each loop):
var func = [];
for(i in 0...256)
func[i] = function() trace(i);
func[0]();
func[127]();
The one you show is the expected/desired behavior. To retain the value of "i" you must use "callback":
/* not pseudo code ;) */
var func = [];
for(i in 0...256)
func[i] = callback(function(v) trace(v), i);
func[0]();
func[127]();
func[256]();
精彩评论