JavaScript匿名函数的参数 [英] Arguments to JavaScript Anonymous Function

查看:102
本文介绍了JavaScript匿名函数的参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆