Take a look at this code:
var arr = new Array();
for (var i = 0; i < 10; i++) {
arr[i] = {
func:function() {
console.log(i);
}
}
}
arr[0].func();
I am confused by this, because I thought this would work. I basically would like each object in the array to print the value it was given when the function was created.
Right now when I call func()
, it prints 10 in the console. Is there a way to make it print 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
instead? Thanks!