javascript - 内部 $.getJSON 不会转到循环中的第二个元素
问题描述
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"
解决方案
有两件事发生:
$.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);
});
}
});
推荐阅读
- php - Kohana auth 模块在使用 Auth::instance()->login 时返回 null
- css - 为多个班级节省翻转卡悬停空间
- java - 加密/解密程序无法正常工作
- android - Play商店预发布报告中的Android应用程序崩溃但在真实设备中工作
- python - Python列表未附加
- excel - 生产日历 - Excel
- python-2.7 - 如果语句带有一个数字数组
- docker - 无法使用 docker 存储库中供应商目录中的包
- angular - 实例变量未在 Observable<> 订阅中分配?
- python - 如何在 HTML 页面中插入 Python 代码?