如何在匿名函数调用中获取外部循环索引? [英] 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
( not shared ),因此它不会被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屋!