我有以下javascript代码:
$.getJSON(url, function(data) { //Make a call to an api with the a url.
// Take the Response field of the json response.
// This field contains objects
var d = data['Response'];
for(var i = 0; i < d.length; i++) { // For each object
var obj1 = d[i];
var id = obj1['id']; // Take the id of the object
var url2 = endpoint+'id='+id
// Make a new api call based on the id of the object
$.getJSON(url2, function(obj2) {
console.log(i)
});
}
});
由于某些原因,它仅打印i
的最后一个值。虽然,当我在内部块外部和i
块内部打印for
的值时,它会打印i
的所有值。
我还尝试使用let
代替var
的{{1}},但是它随机打印i
的值,而不是顺序打印。它还会两次打印一些值。
为什么会这样?
如何在for循环中使内部块打印i
所取的所有值?
答案 0 :(得分:0)
我认为调用回调时是经典问题,如 您是否曾尝试将匿名函数放入循环中类似的问题? 而不是使用let?
$.getJSON(url, function(data) { //Make a call to an api with the a url.
var d = data['Response']; //Take the Response field of the json response. This field contains objects
for(var i = 0; i < d.length; i++) { //For each object
(function(i) { // protects i in an immediately called function
var obj1 = d[i];
var id = obj1['id']; //Take the id of the object
var url2 = endpoint+'id='+id
$.getJSON(url2, function(obj2) { //Make a new api call based on the id of the object
console.log(i)
});
})(i);
}
});