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

查看:29
本文介绍了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天全站免登陆