For this code
function createArrayOfFunctions(y) {
var arr = [];
for(var i = 0; i<y; i++) {
arr[i] = function(x) { return x + i; }
}
return arr;
}
if you use the function
var funs = createArrayOfFunctions(5);
for (var index = 0; index < 5; i++) {
console.log(funs[index](0));
}
You will get the result
5
5
5
5
5
Because the i in { return x + i}
is declared ouside the closure, and all functions uses the same i variable, each function will return the same value if all inputs are the same.
Assign i into a local variable and put the local variable into the function
function createArrayOfFunctions(y) {
var arr = [];
for(var i = 0; i<y; i++) {
let local = i;
arr[i] = function(x) { return x + local; }
}
return arr;
}
Use another function to create the functions which are stored in the arr
function makeFunction(i) {
return function(x) {
return x + i;
}
}
function createArrayOfFunctions(y) {
var arr = [];
for (var i = 0; i < y; i++) {
arr[i] = makeFunction(i);
}
return arr;
}