The solution would be to use let
in for (let i = 0; i < 3; i++)
, as shown in this code:
var funcs = [];
for (let i = 0; i < 3; i++) {
funcs[i] = function() {
console.log("el valor: " + i);
};
}
for (var j = 0; j < 3; j++) {
funcs[j]();
}
If I'm not mistaken, this is due to the scope of var
and let
. The scope of var
is the function it is in (and if it is not within a function, as was your case, it is a global variable), while the scope of let
is the block in which it is define (after the change, only the loop for
).
With var
, when you call the functions of funcs[]
, there is a global variable i
that has the value 3, so that is the value that is returned in the console. Whereas if you use let
, then there is no global variable i
only the "local" value of i
when the function was created and what you expect is returned.