我有以下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]);
});
}
在mymyMethod()内部调用的匿名函数中,i的值为“ 2”。请建议如何在for循环的第一个循环中让i = 0,然后在第二个循环中使i = 0。
使用闭包,这是一个解决方案:
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
(not shared),因此它不会被for循环所覆盖,for循环会导致问题(i
shared):)
干杯
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句