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]
它说, j
是undefined
因为它循环了userId
每个值。 我想为每个userId
的response
获取相应的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))); }