这个问题在这里已有答案:
我有这个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
用于i
,但它随机打印i
的值,而不是顺序打印。它还会打印两次值。
为什么会这样?如何让内部块打印i
在for循环期间所需的所有值?
我认为在调用回调时是经典问题,如同在类似问题中提到的那样,您是否尝试将匿名函数放入循环中?而不是使用让?
$.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);
}
});