Here is my dilemma.
I’ve got this section of code:
var list_of_numbers = new Array();
function AddToArray(func)
{
// Add to the *beginning* of the array
// essentially reversing the order
list_of_numbers.unshift(func);
}
function DisplayNumber(num)
{
document.write(num);
}
for(var i=0;i<5;++i)
{
AddToArray(function() { DisplayNumber(i); });
}
for(var i=0;i<5;++i)
{
list_of_numbers[i]();
}
What is supposed to happen is that 5 inline functions will be added to the array – each taking a copy of i. However this does not happen.
Expected output:
43210
Actual output:
01234
You have two separate issues, both related to scope.
The anonymous function you’re passing to
AddToArrayis bound to the variablei, not the current value. To address this, we create a new function, and pass in the currenti.JavaScript has function scope, so when you re-declare
iin the second loop, you’re still modifying the same variable. Thus, we rename it toj.If only the first were an issue, you would get 55555, since all functions would use the same
i, at that point 5. However, since you reuseifor the second index,iis set to the current loop index.