I have a code:
Demo jsFiddle
which loop three times, each time creating a new function that returns the loop sequence number.
I expected to see the loop sequence inser to array : 0, 1, and 2.
a[i] = function() {
return i;
}
everything looks normal but when I try to print the array I got
the resualt:
arr[0] is =>function () { return i; }
arr[1] is =>function () { return i; }
arr[2] is =>function () { return i; }
the code:
function f() {
var a = [];
var i;
for (i = 0; i < 3; i++) {
a[i] = function() {
return i;
}
}
return a;
}
var arr = f();
for (var index = 0; index < arr.length; index++) {
document.write("<b>arr[" + index + "] is </b>=>" + arr[index] + "<br>");
}
why I don’t get the resualt 0, 1, and 2. ?
many thx.
Because
a[i]is a function, not the returned value from the function. So basically you are filling your array with three function bodies, so when you retrieve any of them, you are getting back the body of the function. You can try to doa[i].call()to call the function returned but then you’d get 3 for each invocation, which in line with what Pointy has pointed out in the comment. Because that was the last value when the loop was called, i became 3 right before the loop stoppedSee the fiddle