0

I've got an array which has some strings inside it. I looped on it:

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);
            .........

In the $.getJson line it works.It sends the correct data and get responded also with the correct one, But in console.log(channels[i]); it returns undefined.

BenG
  • 14,826
  • 5
  • 45
  • 60

1 Answers1

0

you need a closure:-

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);
  
}
BenG
  • 14,826
  • 5
  • 45
  • 60