views:

80

answers:

4
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

A: 

All the functions/methods can be used as callbacks only. When you call the callback function you pass variables to it.

var myclass = {
  foo: function(params, callback){
    // do some stuff
    callback(variable1, variable1, variableN);
  }
}
Anpher
+1  A: 

How about a closure:

for (var i = 0; i < somearray.length; i++) {
    var val = somearray[i][0];
    myclass.foo({'arg1': val}, function(v) {
      return function() {console.log(v) };
    }(val) );
}
Tomalak
A: 
for (var i = 0; i < somearray.length; i++)

{
    myclass.foo({'arg1':somearray[i][0]}, function(somearray)
    {
        console.log(somearray[i][0]);
    });
}

And then in method foo call anonymous function with param.

Alexey Ogarkov
+7  A: 

The i in the anonymous function captures the variable i, not its value. By the end of the loop, i is equal to somearray.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:

function makeFunc(j) { return function() { console.log(somearray[j][0]); } }

for (var i = 0; i < somearray.length; i++)
{
    myclass.foo({'arg1':somearray[i][0]}, makeFunc(i));
}

makeFunc's argument could have been named i, but I called it j to show that it's a different variable than the one used in the loop.

Amnon
+1 for giving a good explanation of the problem, as well as providing a solution!
Matt
I got your point. Thanks. But I just cant figure out how to call makeFunc.
Phonethics
Awesome ! I got my problem solved. This is totally a new thing for me in JavaScript !
Phonethics