如何在匿名函数调用中获取外循环索引? [英] How to get outer loop index inside anonymous function call?
问题描述
我有以下 javascript 代码:
I have the following javascript code :
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.
Inside the anonymous function called inside my myMethod(), value of i is '2'. Please suggest how to get i = 0 in first cycle of for loop and then 1 in the second loop.
推荐答案
使用闭包,这是一个解决方案:
With a closure, this a solution:
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
,它也能用.
I changed the original counter to x
to make it more understandable (so you dont confuse that variable with the original i
), but if it keeps named also i
, it will work, too.
这样,每个循环周期都有自己的变量 x
(不共享),所以它不会被 for 循环覆盖,这导致了问题(i
已共享) :)
This way, each loop cycle has it's own variable x
(not shared), so it doesn't get overwritten by the for loop, which was causing the problem (i
was shared) :)
干杯
这篇关于如何在匿名函数调用中获取外循环索引?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!