I came across this behavior while trying to write some tests for my code and was wondering if somebody could explain to me why this isn't performing as I expect it to.
I have the following code:
var arr = [];
for (i = 0; i < 5; i++) {
console.log('pushing %s', i);
arr.push(function() {
console.log('logging %s - random %s', i, Math.random());
});
}
for (ai in arr) {
arr[ai]();
}
which outputs out something like this:
pushing 0
pushing 1
pushing 2
pushing 3
pushing 4
logging 5 - random 0.35618519759736955
logging 5 - random 0.4480402651242912
logging 5 - random 0.9252766149584204
logging 5 - random 0.4456857305485755
logging 5 - random 0.14507507369853556
though I was expecting it to output something like this:
pushing 0
pushing 1
pushing 2
pushing 3
pushing 4
logging 0 - random 0.35618519759736955
logging 1 - random 0.4480402651242912
logging 2 - random 0.9252766149584204
logging 3 - random 0.4456857305485755
logging 4 - random 0.14507507369853556
How is i
changing after I've already pushed to the array? and why does i
resolve to 5
in the logging ...
lines even though it only reaches 4
in the pushing ...
lines?