array1
是["orange","blue"]
。
$.getJSON("path1.json",function(array1){
for (var i = array1.length - 1; i >= 0; i--) {
var path2 = array1[i];
console.log(path2);
$.getJSON(path2,function(someObject){
console.log("Inside the second $.getJSON function");
console.log(path2);
});
}
});
输出看起来像这样。
"orange"
"blue"
"Inside the second $.getJSON function"
"blue"
"Inside the second $.getJSON function"
"blue"
为什么不是输出?
"orange"
"Inside the second $.getJSON function"
"orange"
"blue"
"Inside the second $.getJSON function"
"blue"
答案 0 :(得分:1)
有两件事发生:
$.getJSON()
是部分异步的。这意味着您的回调是异步发生的。var
声明的变量的作用域为函数,而不是块的作用域,并且尽管您可以使用var
在给定范围内重新声明变量,但这样做没有效果。当您将这些东西结合在一起时,您会遇到以下情况:for
循环的所有迭代都在调用任何回调之前完成,因此,在发生回调时,path2
已经更新了几次。 (巧合的是,这实际上并不影响内部$.getJSON()
本身,因为path2
是按值传递的。)
过去,我们必须修正path2
的值范围(通常通过IIFE),以使其在执行回调之前不会被覆盖:>
$.getJSON("path1.json", function(array1){
for (var i = array1.length - 1; i >= 0; i--) {
var path2 = array1[i];
console.log(path2);
$.getJSON(path2,
function(path2) {
return function(someObject){
console.log("Inside the second $.getJSON function");
console.log(path2);
};
}(path2)
);
}
});
这几天,我们有了let
,它将变量的作用域限定在块中。 for
的块作用域在每次迭代时都是新创建的,并且每次创建回调函数时,该作用域实例都将绑定到回调,因此可以进行以下工作:
$.getJSON("path1.json",function(array1){
for (var i = array1.length - 1; i >= 0; i--) {
let path2 = array1[i];
console.log(path2);
$.getJSON(path2, function(someObject){
console.log("Inside the second $.getJSON function");
console.log(path2);
});
}
});