Question

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

Was it helpful?

Solution

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](); 
}​
  1. The anonymous function you're passing to AddToArray is bound to the variable i, not the current value. To address this, we create a new function, and pass in the current i.

  2. JavaScript has function scope, so when you re-declare i in the second loop, you're still modifying the same variable. Thus, we rename it to j.

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top