JavaScript 匿名函数的参数
for (var i = 0; i < somearray.length; i++)
{
myclass.foo({'arg1':somearray[i][0]}, function()
{
console.log(somearray[i][0]);
});
}
如何将某个数组或其索引之一传递到匿名函数中? somearray 已经在全局范围内,但我仍然得到 somearray[i] 未定义
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
匿名函数中的
i
捕获变量i
,而不是它的值。在循环结束时,i
等于somearray.length
,因此当您调用该函数时,它会尝试访问不存在的元素数组。您可以通过创建一个捕获变量值的函数构造函数来解决此问题:
makeFunc
的参数本来可以命名为i
,但我将其称为j< /code> 以表明它是与循环中使用的变量不同的变量。
The
i
in the anonymous function captures the variablei
, not its value. By the end of the loop,i
is 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 itj
to show that it's a different variable than the one used in the loop.闭包怎么样:
How about a closure:
然后在方法 foo 中使用参数调用匿名函数。
And then in method foo call anonymous function with param.
您可以使用回调将变量值传递给烦人的函数,
像
检查这篇文章: https://shahpritesh.wordpress.com/2013/09/06/javascript-function-in-loop-passing-dynamic-variable-value/
You can pass variables values to annoymous function by using callback,
something like
check this post: https://shahpritesh.wordpress.com/2013/09/06/javascript-function-in-loop-passing-dynamic-variable-value/
所有函数/方法只能用作回调。当您调用回调函数时,您将变量传递给它。
All the functions/methods can be used as callbacks only. When you call the callback function you pass variables to it.