Arguments to JavaScript Anonymous Function

前端 未结 5 878
悲&欢浪女
悲&欢浪女 2021-02-13 11:47
for (var i = 0; i < somearray.length; i++)
{
    myclass.foo({\'arg1\':somearray[i][0]}, function()
    {
        console.log(somearray[i][0]);
    });
}
5条回答
  •  南笙
    南笙 (楼主)
    2021-02-13 12:02

    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.

提交回复
热议问题