For循环在asynchronous编程

userId = ['123', '456']; userName = ['aaa', 'bbb']; for (var j = 0; j < userId.length; j++) { Instagram.otherUserMedia(userId[j], function (response) { $('#otherInfo').append('<h2>' + userName[j] + '</h2>'); for(var i = 0; i < response.data.length; i++) { $('#otherInfo').append('<img src="' + response.data[i].images.thumbnail.url + '" />'); } }); } 

在这个代码片段中,我需要显示相应的userName与来自response的输出图像。 但是当我执行这个代码时, j值递增,直到userId.length ,然后进入callback。 所以,当我想显示userName[j]它说, jundefined因为它循环了userId每个值。 我想为每个userIdresponse获取相应的userName

这是一个与JavaScriptclosures有关的问题。

下面的演示可能是其中一个解决scheme;

 userId = ['123', '456']; userName = ['aaa', 'bbb']; for (var j = 0; j < userId.length; j++) { Instagram.otherUserMedia(userId[j], (function(index) { return function(response) { $('#otherInfo').append('<h2>' + userName[index] + '</h2>'); for (var i = 0; i < response.data.length; i++) { $('#otherInfo').append('<img src="' + response.data[i].images.thumbnail.url + '" />'); }; } }(j))); }