2014-03-04 55 views
0

比方說我有以下代碼:

for(var i=0; i < itemlist.length; i++){ 
    var item = itemlist[i]; 
    var id = item.id; 
    $http.get(id + '.json').success(function(data){ 
     //do something with data. 
     console.log(item.name); 
    } 
} 

在控制檯中顯示的名稱將是一個重複的值(我認爲陣列ITEMLIST的第一個值),即回調函數不知道可變項目。

隨着我的理解水平這是奇怪的。有沒有辦法將其他變量傳遞給此回調函數 - 和/或 - 有人可以啓發我爲什麼此變量的作用域以這種方式運行?

+0

應該對就好了關閉。 –

+0

[在循環中創建閉包:常見錯誤](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Closures#Creating_closures_in_loops.3A_A_common_mistake)&http://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example –

回答

2

假設ITEMLIST是一個數組,你可以使用angular.forEach()

angular.forEach‎ (itemlist, function (item, i) { 
    var id = item.id; 
    $http.get(id + '.json').success(function (data) { 
     //do something with data. 
     console.log(item.name); 
    }) 
}) 

的問題,因爲我的評論指出的是在循環錯誤使用閉包變量的。

如果你想support only IE9+話,你甚至可以用Array.forEach()

itemlist.forEach‎ (function (item, i) { 
    var id = item.id; 
    $http.get(id + '.json').success(function (data) { 
     //do something with data. 
     console.log(item.name); 
    }) 
}) 
+0

非常感謝解決方案**和**解釋! – Titus

+0

...或者'itemlist.forEach(function(item,i){...});'[支持的不錯](http://kangax.github.io/es5-compat-table/#Array .prototype.forEach)? –

+0

@JanTuroň是的...在我目前的項目中我需要支持IE8 +,所以我總是最終使用這些庫函數.... –

0

將值與一個回調函數,你應該使用綁定的關聯。 這樣,您就可以通過this.object附加任何對象回調和訪問:

function yourFunction() { 
    for(var i=0; i < itemlist.length; i++){ 
    var item = itemlist[i]; 
    var id = item.id; 
    var onSuccess = onSuccess.bind({item: item}); 
    $http.get(id + '.json').success(onSuccess); 

}

function onSuccess(data) { 
    console.log(this.item.name); 
} 
相關問題