【问题标题】:For loop and ForEach loop exhibit different behaviors with getJSONFor 循环和 ForEach 循环使用 getJSON 表现出不同的行为
【发布时间】:2018-02-02 16:32:07
【问题描述】:

我正在尝试从 api 获取数据,但我使用的 For 循环在嵌套的 GetJSON 调用中返回具有 null 和未定义值的对象,但是当我尝试 forEach 循环时它工作正常。 有什么想法吗?

var baseUrl = "https://wind-bow.gomix.me/twitch-api/";
var channels = ["ESL_SC2", "FreeCodeCamp", "Test_channel", "brunofin"];

//**First function with forEach. WORKS FINE**
function getDataForEach() {

    channels.forEach(function(channel) {

        $.getJSON(txtUrl('streams', channel), function(json) {
            console.log(json);

            $.getJSON(txtUrl('channels', channel), function(json2) {
                console.log(json2);

            });
        });

    });
}

//**Second function with a normal for loop. The 2nd JSON doesnt return the proper data**

function getDataForLoop() {
        for (i=0;i<channels.length;i++){
            $.getJSON(txtUrl('streams', channels[i]), function(json) {
                console.log(json);

                //THIS 2nd call doesnt returns undefined objects. 
                $.getJSON(txtUrl('channels', channels[i]), function(json2) {
                    console.log(json2);

                });
            });

        });
    }

function txtUrl(prop, chnl) {
    return baseUrl + prop + '/' + chnl + '?callback=?';
}

$(document).ready(function() {
            getData();
});

【问题讨论】:

  • 您是否尝试在第二次调用中设置断点并检查i 的值?
  • 是的。现在我明白为什么它不起作用了。

标签: javascript jquery ajax foreach getjson


【解决方案1】:

getJSON 是异步的,因此它的回调函数不会立即执行,因此在for 循环的情况下,如果您在回调中使用i,它将产生this error

我注意到的另一件事是您使用全局 i,它也是 source of troubles

如果您使用的是 ECMAScript 6,您可以使用 let 声明 i

for(let i = 0; ...)

let 是块范围的,因此使用它不会在上面的第一个链接中产生错误。

【讨论】:

  • 谢谢。我不知道 Javascript 中这个隐含的全局事物。
【解决方案2】:

我认为这与 forEach 是一个回调函数而 for 不是这一事实有关。所以 for 在接收到数据之前执行。

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach

【讨论】:

    猜你喜欢
    • 2016-05-23
    • 2011-05-19
    • 1970-01-01
    • 1970-01-01
    • 2021-03-12
    • 1970-01-01
    • 2012-01-27
    • 2019-04-04
    相关资源
    最近更新 更多