数组返回undefined

时间:2016-05-02 11:07:21

标签: jquery

我有一个数组里面有一些字符串。我循环使用它:

for(var i = 0; i < channels.length; i++) {
        $.getJSON('https://api.twitch.tv/kraken/streams/' + channels[i] + '?callback?', function(response) {
            console.log(channels[i]);
            console.log(response);
            .........

$.getJson行中,它会发挥作用。它会发送正确的数据,并使用正确的数据进行回复,但在console.log(channels[i]);中,它会返回undefined

1 个答案:

答案 0 :(得分:0)

你需要一个闭包: -

for (var i = 0; i < channels.length; i++) {
  
  (function(i) {
    
    $.getJSON('https://api.twitch.tv/kraken/streams/' + channels[i] + '?callback?', function(response) {
      console.log(channels[i]);
      console.log(response);
    });
    
  })(i);
  
}

相关问题