What you want to do is bind the variable within each function to a separate, unchanging value outside of the function:
var funcs = []; function createfunc(i) { return function() { console.log("My value: " + i); }; } for (var i = 0; i < 3; i++) { funcs[i] = createfunc(i); } for (var j = 0; j < 3; j++) { funcs[j](); //let's run see this. }
What you want to do is bind the variable within each function to a separate, unchanging value outside of the function:
var funcs = []; function createfunc(i) { return function() { console.log("My value: " + i); }; } for (var i = 0; i < 3; i++) { funcs[i] = createfunc(i); } for (var j = 0; j < 3; j++) { funcs[j](); //let's run see this. }
Question and answer is powered by AnsPress.io