for (var i = 0; i < somearray.length; i++)
{
myclass.foo({'arg1':somearray[i][0]}, function()
{
console.log(somearray[i][0]);
});
}
How do I pass somearray or one of its indexes into the anonymous function ?
somearray is already in the global scope, but I still get somearray[i] is undefined
The
iin the anonymous function captures the variablei, not its value. By the end of the loop,iis equal tosomearray.length, so when you invoke the function it tries to access an non-existing element array.You can fix this by making a function-constructing function that captures the variable’s value:
makeFunc‘s argument could have been namedi, but I called itjto show that it’s a different variable than the one used in the loop.