I have code that looks like this:
var a = [];
for(var i = 0; i < 10; i++) {
a[i] = function() {
console.log(i);
}
}
Unfortunately, it seems that i
is being passed by reference, so all the functions in a
output 10. How do I make it so that each function outputs the value that i
had when it was created? I.e. a[0]()
gives 0, a[1]()
gives 1, etc.
EDIT: to clarify, I do not want a
to store the values 0-9. I want a
to store functions that return the values 0-9.