javascript - 如何在匿名函数调用中获取外循环索引?

标签 javascript anonymous-function

我有以下 javascript 代码:

var Person = [['John', 0, 0, 0],['Chris', 1, 0, 0]];
for (i = 0; i < Person.length; i++ )
{
    someObj.myMethod(Person[i][0], function (object) {
        console.log(i); //this prints 2, I want 0 and 1 as per the loop

        //here I want to access other members of Person[i] array, like Person[i][1], Person[i][2] and Person[i][3]
        //but these console.log() print 'undefined' because i = 2 !!
        console.log(Person[i][1]);
        console.log(Person[i][2]);
        console.log(Person[i][3]);
    });
}

在我的 myMethod() 中调用的匿名函数中,i 的值为“2”。请建议如何在 for 循环的第一个循环中获得 i = 0,然后在第二个循环中获得 1。

最佳答案

有了闭包,这是一个解决方案:

var Person = [['John', 0, 0, 0],['Chris', 1, 0, 0]];
for (x = 0; x < Person.length; x++ )
{
    (function(i){   //We add a closure
        someObj.myMethod(Person[i][0], function (object) {
          console.log(i);
          console.log(Person[i][1]);
          console.log(Person[i][2]);
          console.log(Person[i][3]);
      });
    })(x);      //Call the closure function with the value of the counter
}

我将原始计数器更改为 x 以使其更易于理解(这样您就不会将该变量与原始的 i 混淆),但如果它保持命名也 i,它也会起作用。

这样,每个循环周期都有它自己的变量 x(不共享),所以它不会被 for 循环覆盖,这导致了问题(i 已共享):)

干杯

关于javascript - 如何在匿名函数调用中获取外循环索引?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21010963/

相关文章:

javascript - 计算数组中字符串的出现次数(javascript)

javascript - 使用 JS 循环从 HTML 按钮发送唯一的变量来运行

javascript - Way 不会将参数传递给匿名函数导致它返回一个函数

Javascript "this"通过不同的范围

javascript - 为什么我必须在 React 的匿名函数中包装我的 onClick 属性的函数?

javascript - 跳过范围内的一个字符

javascript - jQuery $(this).position().top 在 Chrome 中不起作用

javascript - Jsf 命令按钮调用 javascript 函数然后刷新整个页面

javascript - 为什么匿名函数在 Javascript 中对我不起作用?

matlab - 如何在匿名函数中使用条件