我有以下 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/