我有以下的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的內部匿名函數,我的價值是 '2'。請建議如何在for循環的第一個循環中獲取i = 0,然後在第二個循環中創建1。
查看http://stackoverflow.com/questions/111102/how-do-javascript-closures-work – tewathia
你可以檢查下劃線的每個函數, – jingyinggong
(())會完成,someObj.myMethod( Person [i] [0],function(object){這個函數是一個回調函數,所以我已經設置爲2! – jingyinggong