javascript - 我的回调函数似乎没有填充我的数组?

标签 javascript jquery json callback get

我的回调函数有问题。我的代码应该向 REST API 发出 16 个 GET 请求,以提取 16 个不同的 JSON 文件。然后,它需要将每个 JSON 解析为该周足球积分榜排名的字典,并最终将每个条目保存到“字典的字典”HistoricalTable 中,以给出过去 16 周的联赛排名。但是,当我运行关联的回调函数时,各种 LeagueTable 变量似乎工作正常,但是当我尝试将它们保存到历史数据中时,最终的数组似乎每个都有相同的 LeagueTable 条目,如下所示。

Here is an image of the console output for my final table. Each entry should be different, whereas each entry seems to be the most recent week.

//This creates the modifier for the URL used in the GET request
var MatchDayList = []
for (i = 0; i < 17; i++) {
  MatchDayList[i] = i
}
MatchDayList.shift()

var HistoricalTable = {}
var LeagueTable = {}

// This executes the GET request
for (i = 0; i < 16; i++) {
  url = 'http://api.football-data.org/v1/competitions/445/leagueTable/?matchday=' + MatchDayList[i],

    $.ajax({
      url: 'http://api.football-data.org/v1/competitions/445/leagueTable/?matchday=' + MatchDayList[i],
      headers: {
        'X-Auth-Token': ''
      },
      method: 'GET',
      dataType: 'json',
      success: function(data) {
        handleData(data)
      },

    });
}
//This function should append the retrieved JSON to the LeagueTable variable
function handleData(data) {
  for (var j = 0; j < 20; j++) {
    LeagueTable[data.standing[j].position] = data.standing[j].teamName
    LeagueTable[20] = data.matchday
  }
  saveData(LeagueTable)
}
//This function should save each LeagueTable matchday data into a bigger array, HistoricalTable
function saveData(LeagueTable) {
  HistoricalTable[LeagueTable[20]] = LeagueTable
  console.log(HistoricalTable)
}

最佳答案

您在整个代码中使用单个 LeagueTable 变量。因此,每次调用 handleData 都会填​​充相同的 LeagueTable,然后告诉 saveData 将其存储在主表中。因此,您最终会得到 16 个对同一个表的引用。

要解决这个问题,只需将变量声明移动到 handleData 函数中即可:

    function handleData(data) {
      var LeagueTable = {};
      for (var j = 0; j < 20; j++) {
        LeagueTable[data.standing[j].position] = data.standing[j].teamName
        LeagueTable[20] = data.matchday
      }
      saveData(LeagueTable)
    }

顺便说一句,您的 url 变量没有在任何地方声明,因此它最终位于全局范围内,这通常是不好的做法。与 for 循环内的 i 索引相同。

关于javascript - 我的回调函数似乎没有填充我的数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47781853/

相关文章:

javascript - ReduxThunk 如何将 Action 数据传递到原始状态?

javascript - 在一个函数中获取多个 JSON 文件

android - Android应用程式当机。将JSON数据放入Listview

javascript - 如何在 AngularJS 中搜索并返回 JSON 资源的特定索引?

javascript - 传单不会显示我的标记, "TypeError: t is null"

c# - DataContractJsonSerializer 和 JavaScriptSerializer 有什么区别?

javascript - 检查整数是否包含数字javascript

javascript - 如何使用 jquery 连接 "this"和附加字符串选择器?

javascript - PHP MySQL JavaScript

javascript - addClass 转换不起作用