1
 <script>
        /* 1st API*/
        $.getJSON("http://cricapi.com/api/matches/?apikey=6aP8B4MImxSNxI6fevBmC2ZshO42",function(data){
         var len = data.matches.length;
         for(i=0;i<len;i++){

              id = data.matches[i].unique_id;
              ms = data.matches[i].matchStarted;
              x = data.matches[i].date;
              team_1 = data.matches[i]['team-1']
               /* 2nd  API*/
             $.getJSON("https://cricapi.com/api/cricketScore/?apikey=6aP8B4MImxSNxI6fevBmC2ZshO42&unique_id="+id,function(data1){
                    console.log(team_1);

                              });
                 }
  });

why i cannot get the team_1 of each match in second getJSON(). It is giving the output of same team name multiple times please help me to get the team names of each match. Appreciate any help!!

Vinay sharma
  • 745
  • 5
  • 14
  • Does this answer your question? [JavaScript closure inside loops – simple practical example](https://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example) – Terry Jan 14 '20 at 13:25

2 Answers2

1

This "bug" is caused by hoisting.

Index i is stored as var, and it isn't in local for loop scope, so, when the index has gained its final value, the same value is used.

You can use let keyword:

for(let i=0;i<len;i++){ ..

so the variable will be loop scoped

Also Check out this link

Mosè Raguzzini
  • 15,399
  • 1
  • 31
  • 43
-2
function getScore(id, callback) {
    $.getJSON("https://cricapi.com/api/cricketScore/?apikey=6aP8B4MImxSNxI6fevBmC2ZshO42&unique_id="+id, function(data1) {
        callback(data1);
    });
}

$( document ).ready(function() {
    $.getJSON("http://cricapi.com/api/matches/?apikey=6aP8B4MImxSNxI6fevBmC2ZshO42",function(data){
        var len = data.matches.length;
        for(i=0;i<len;i++){
            id = data.matches[i].unique_id;
            ms = data.matches[i].matchStarted;
            x = data.matches[i].date;
            team_1 = data.matches[i]['team-1']
            /* 2nd  API*/
            getScore(id, function(data1) {
                console.log(data1);
            });
        }
    });
});
Pedram Parsian
  • 3,750
  • 3
  • 19
  • 34