Reputation: 49
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?
Upvotes: 1
Views: 151
Reputation: 5859
i could do like so :
var funcs = [];
for (var i = 0; i < 10; i++) {
(function (i) {
funcs[i] = function () {
return i;
};
})(i);
}
alert(funcs[3]());
creating a separate activation frame for each iteration
you can alternatively use map:
var numbers = [];
for (var i = 0; i < 10; i++) {
numbers.push(i);
}
var funcs = numbers.map(function (i) {
return function () { return i; };
});
alert(funcs[3]());
Upvotes: 2
Reputation: 4091
var funcs = [];
for (var i = 0; i < 10; i++) {
funcs[i] = makeFunction(i);
}
function makeFunction(i) {
return function() {
return i;
}
}
i
in the returned function is bound to the local variable i
in makeFunction
rather than i
in your main block of code.
Upvotes: 0