我的回调函数有问题。我的代码应该向REST API发出16个GET请求以提取16个不同的JSON文件。然后,它需要将这些JSON中的每一个解析为该周足球桌排名的字典,并最终将每个条目保存为字典的字典,历史表,以给予过去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)
}
答案 0 :(得分:0)
您在整个代码中使用单个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
索引相同。