从API获取数据:为何无法遍历JavaScript中的playedGames数组?
问题原因与解决方案
问题根源
你的代码里,then回调的for循环在第一次迭代时就执行了return,这会直接终止函数,循环根本没机会执行后续迭代,所以只能返回第一个游戏的对战信息。另外硬写循环条件i < 12也不灵活,应该根据数组实际长度来遍历。
修正方案
方案1:使用map方法(更简洁)
map方法可直接遍历数组,把每个元素转换成你需要的对战字符串,最后返回整个结果数组:
export function getMatchData() { return fetch('https://stryk.herokuapp.com/strycket2022') .then(response => response.json()) .then(data => { return data.playedGames.map(game => `${game.teams[1].name} VS ${game.teams[2].name}`); }); }
方案2:用for循环收集结果
先创建空数组,把每个对战信息push进去,循环结束后再返回这个数组:
export function getMatchData() { return fetch('https://stryk.herokuapp.com/strycket2022') .then(response => response.json()) .then(data => { const matchInfos = []; // 用数组长度作为循环上限,适配任意数量的游戏 for (let i = 0; i < data.playedGames.length; i++) { const game = data.playedGames[i]; matchInfos.push(`${game.teams[1].name} VS ${game.teams[2].name}`); } return matchInfos; }); }
之后你拿到这个数组,就可以遍历它,在表格的每一行插入对应的对战信息了。
内容的提问来源于stack exchange,提问作者Lukas E
相关产品推荐
相关产品推荐

