首页 > 解决方案 > 内部 $.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"

标签: javascriptjquerygetjson

解决方案


有两件事发生:

  • $.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);
        });
    }
});

推荐阅读