1

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?

sonaxaton
  • 49
  • 1
  • 7
  • how about declaring a local variable whose value is `i` within that function and return it instead?. – qtgye Feb 17 '15 at 04:55
  • Obviously this is simplified code but if your functions differ only by the value of i it seems the "i" should really just be an argument. – ReallyMadeMeThink Feb 17 '15 at 05:02
  • call a function, creating a separate activation frame for each iteration – ZEE Feb 17 '15 at 05:05
  • 1
    Welcome to [so]! I believe this should answer your question: [JavaScript closure inside loops – simple practical example](http://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example). If it doesn't, please let me know. – Qantas 94 Heavy Feb 17 '15 at 05:06
  • Yes thank you that does answer it. I wasn't really sure what to search for. – sonaxaton Feb 17 '15 at 14:18

2 Answers2

2

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]());
ZEE
  • 5,669
  • 4
  • 35
  • 53
0
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.

radiaph
  • 4,001
  • 1
  • 16
  • 19