【问题标题】:My callback functions don't seem to fill in my array?我的回调函数似乎没有填充我的数组?
【发布时间】:2017-12-12 21:29:02
【问题描述】:

我的回调函数有问题。我的代码应该向 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)
}

【问题讨论】:

    标签: javascript jquery json callback get


    【解决方案1】:

    您在整个代码中使用了一个 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 索引相同。

    【讨论】:

    • 这太棒了!我已经盯着这个看了好几个小时了,无法找到答案。非常感谢您花时间回答!
    猜你喜欢
    • 2020-07-14
    • 2010-12-11
    • 2017-03-20
    • 1970-01-01
    • 1970-01-01
    • 2022-01-12
    • 1970-01-01
    • 2019-08-30
    • 2013-06-13
    相关资源
    最近更新 更多