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