I'm not really sure how to word this question better, but basically my problem is this:
I have code like this (not exactly, this code is really simple and mine is a little more complicated):
var funcs = [];
for (var i = 0; i < 10; i++) {
funcs[i] = function() { return i; };
}
So the idea is that each function in funcs
will return each number from 0 to 9 when called. But the problem is that each one is still referring to the variable i
when called, so they will all return 9. How do I get this work as intended (i.e. for all n, funcs[n]() === n
)? How do I get each function scope to capture only the current value of i
, not the value that changes?