JavaScript匿名函数的参数 [英] 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]);
});
}
如何将somearray或其中一个索引传递到匿名函数?
somearray已经在全局范围,但我仍然得到 somearray [i]未定义
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
推荐答案
匿名函数中的 i
捕获 i
值。在循环结束时, i
等于 somearray.length
,所以当你调用函数时,访问不存在的元素数组。
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
参数可以命名为 i
,但我调用 j
来显示它是一个不同的变量
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.
这篇关于JavaScript匿名函数的参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!