2011-08-26 76 views
2

我正在調用一個需要回調函數作爲參數的異步函數。Javascript - 在回調函數中添加更多參數

下面是javascript代碼:

for(i in array) 
{ 
    var item = array[i]; 
    functionToCall(item[i][1], 50, function(a, b) 
    { 
     alert(a + b); 
    }); 
} 

我不能編輯functionToCall功能。我想要做的就是像這樣在回調函數中使用「item」變量。

for(i in array) 
{ 
    var item = array[i]; 
    functionToCall(item[i][1], 50, function(a, b, c) 
    { 
     alert(a + b + c); 
    }, item); 
} 

但是這段代碼無法正常工作。我不能只在函數內使用「item」,因爲它總是使用數組中的最後一項。

那麼我該怎麼做呢?

回答

4

您可以在函數內使用item,但需要「捕獲」它,以便每次最終都不要使用數組的最後一個元素。

for(var i = 0, l = array.length; i < l; ++i) { // better than for .. in 
    var item = array[i]; 
    (function(item, i){ 
     functionToCall(item[i][1], 50, function(a, b) // do you really re-index item with the same index? 
     { 
      alert(a + b); 
     }); 
    })(item, i); 
} 
+0

它比預期的要好,非常感謝! – Marm

0

使用for..in迭代數組是個壞主意。而是使用.forEach(),有很多你的問題走開:

array.forEach(function(item) 
{ 
    functionToCall(item[1], 50, function(a, b) 
    { 
     alert(a + b + item[1]); 
    }); 
} 

要在舊的瀏覽器使用.forEach()see this

0

我會嘗試這樣的事:

function createExecutionCall(itemIndex, number, item) 
{ 
     return function() { functionToCall(itemIndex, number, function(a, b) 
     { 
      // Example, item should be contained within this closure then 
      alert(a + b + item); 
     }); 
} 

for(i in array) 
{ 
    var item = array[i]; 

    var call = createExecutionCall(item[i][1], 50, item); 
    call(); 
    }