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 inlin开发者_高级运维e 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.
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)
{
(function(i)
{
AddToArray(function(){ DisplayNumber(i); });
})(i);
}
for(var j=0;j<5;++j)
{
list_of_numbers[j]();
}
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 reuse i for the second index, i is set to the current loop index.
加载中,请稍侯......
精彩评论