繁体   English   中英

为什么我的for循环在我的JSON函数中不起作用?

[英]Why is my for loop not working in my JSON function?

大家好,我现在在Twitch Viewer上编码和工作。 (FreeCodeCamp)

我能够从JSON文件中获取信息并通过我的html代码显示它。 但是我的问题是我无法从“游戏”数组中获取名称。

为什么for循环在json函数中不起作用?

非常感谢您的帮助!

 var gamer = ["OgamingSC2","ESL_SC2"]; for(i=0;i<(2);i++){ $.getJSON('https://api.twitch.tv/kraken/streams/'+gamer[i]+'/?callback=?', function(json) { $('.list').append("<b>Name: " + gamer[i] + "</b><br>"); var logo = json.stream.channel.logo; $('.list').append("Game: " + json.stream.channel.game + "<br>"); $('.list').append("Status: " + json.stream.channel.status + "<br>"); $('.list').append("Logo: " + "<img src=" + logo + ">" + "<br><br><br>"); console.log(json); });} 
 img { width: 5em; border-radius: 10px; } 
 <head><script src="http://code.jquery.com/jquery-1.11.2.min.js"></script> </head> <body> <b>Twitch.tv JSON API</b> </br> <div class="list"></div> </body> 

这里发生的是$.getJson是一个异步调用,这意味着它仅在执行所有同步操作后才会执行。 因此, for循环运行两次,并将两个getJSON回调函数添加到函数堆栈中。

现在,由于Javascript具有词法或函数作用域,因此变量i在全局作用域中仍为2 (因为最后的i++也已执行)。

接下来,从函数堆栈中逐个执行回调函数。 但是, i ,您的变量i现在为2! 现在,回调函数将仅看到不存在的gamer[2]并抛出undefined

如果将console.log(i)添加到$ .getJSON,您将看到它仅输出2次。

你为什么不试试这个:

  var gamer = ["OgamingSC2","ESL_SC2"]; gamer.map(function(gamer) { loopIt(gamer); }); function loopIt(gamer) { $.getJSON('https://api.twitch.tv/kraken/streams/'+gamer+'/?callback=?', function(json) { $('.list').append("<b>Name: " + gamer + "</b><br>"); var logo = json.stream.channel.logo; $('.list').append("Game: " + json.stream.channel.game + "<br>"); $('.list').append("Status: " + json.stream.channel.status + "<br>"); $('.list').append("Logo: " + "<img src=" + logo + ">" + "<br><br><br>"); }); } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <head><script src="http://code.jquery.com/jquery-1.11.2.min.js"></script> </head> <body> <b>Twitch.tv JSON API</b> </br> <div class="list"></div> </body> 

我认为它json没有提供任何内容,因为您放置了callback=? 当你通过时? 在回调变量中,它的取值是? 一无所获 因此,只需输入callback= .dont不提供任何值,然后再试一次。 并在功能中警告json变量。 您会知道价值是否来临。 我没有发现循环和json链接有问题。

对于此类for循环中的服务器调用,可以使用自定义循环。

像这样, https://jsfiddle.net/s8eLhxpx/

    var gamer = ["OgamingSC2","ESL_SC2"];

     var initCounter = 0;
     callServerData()

     function callServerData(){
        $.getJSON('https://api.twitch.tv/kraken/streams/'+gamer[ initCounter ]+'/?callback=?', function(json) {
    $('.list').append("<b>Name: " + gamer[ initCounter ] + "</b><br>");
    var logo = json.stream.channel.logo;

     $('.list').append("Game: " + json.stream.channel.game + "<br>");
     $('.list').append("Status: " + json.stream.channel.status + "<br>");
     $('.list').append("Logo: " + "<img src=" + logo + ">" + "<br><br><br>");
      console.log(json);
      initCounter++
      if(initCounter < gamer.length){

        callServerData();
     }

});
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM