Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Arguments to JavaScript Anonymous Function

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

like image 618
Phonethics Avatar asked Jun 11 '10 15:06

Phonethics


People also ask

Do anonymous functions receive arguments?

The anonymous function accepts one argument, x , and returns the length of its argument, which is then used by the sort() method as the criteria for sorting. The expression returned by the lambda function can be assigned to a variable and used in the code at multiple places.

Does JavaScript support anonymous function?

Anonymous Function is a function that does not have any name associated with it. Normally we use the function keyword before the function name to define a function in JavaScript, however, in anonymous functions in JavaScript, we use only the function keyword without the function name.

Can we assign an anonymous function to a variable in JavaScript?

An anonymous function in javascript is not accessible after its initial creation. Therefore, we need to assign it to a variable, so that we can use its value later. They are always invoked (called) using the variable name. Also, we create anonymous functions in JavaScript, where we want to use functions as values.

What is the point of an anonymous function in JavaScript?

An anonymous function is not accessible after its initial creation, it can only be accessed by a variable it is stored in as a function as a value. 3. This function is useful for all scenarios. An anonymous function can be useful for creating IIFE(Immediately Invoked Function Expression).


2 Answers

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.

like image 128
Amnon Avatar answered Sep 19 '22 17:09

Amnon


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) );
}
like image 37
Tomalak Avatar answered Sep 17 '22 17:09

Tomalak