我怎么能得到从api返回的所有值?Javascript



我试图获取API数据并将其插入表中(我使用VS代码和实时服务器)。到目前为止,我已经从ApI获得了正确的数据我的想法是循环该数据并发送它。当我尝试循环数据时,我只得到最后一场发送的足球比赛——为什么我不能得到全部13场比赛?我需要一些关于如何成功的建议。

export function getMatchData() {
return fetch('https://stryk.herokuapp.com/strycket2022')
.then(function (response) {
return response.json();
})

.then(function (data) {

let gameArray = data.playedGames;
let gameInfo = "";
for (let i = 0; i < gameArray.length; i++) {

gameInfo = data.playedGames[i].teams[1].name + " VS " + data.playedGames[i].teams[2].name;

}
console.log(gameInfo);

return gameInfo;



});

如前所述,你每次都在gameInfo变量中设置一个新值,所以你只能看到最后一个值尝试创建一个数组并将值压入其中下面是一个例子:

fetch('https://stryk.herokuapp.com/strycket2022')
.then(response => response.json())
.then(function (data) {
const gameArray = data.playedGames;
let gameInfo = [];
gameArray.ForEach((game) => {
const newGame = game.teams[1].name + " VS " + game.teams[2].name;
gameInfo.push(newGame);
});

console.log(gameInfo);

return gameInfo;
});

创建空数组或对象代替字符串。我是关于可变gameInfo。在每次交互中,你都必须添加新值(例如,如果它将是array,则需要添加gameInfo.push(value))。因此,您将获得包含每个项目信息的数组。你将能够使用它来实现你的目标

在你的变量中,你在每次迭代时重写gameInfo中的值,在循环结束时,你只得到最后一个值

也许这会帮助你走上正确的轨道?

fetch('https://stryk.herokuapp.com/strycket2022')
.then(response=>response.json())
.then(function (data) {
let gameArray = data.playedGames;
let gameInfo = [];
for (let i = 0; i < gameArray.length; i++) {
gameInfo.push( data.playedGames[i].teams[1].name + " VS " + data.playedGames[i].teams[2].name);
}
console.log(gameInfo.join("n"));
});

或者更短:

fetch('https://stryk.herokuapp.com/strycket2022')
.then(r=>r.json())
.then(dat=>console.log(dat.playedGames.map(g=>g.teams[1].name+" vs "+g.teams[2].name).join("n")));

const res = await fetch('https://stryk.herokuapp.com/strycket2022')
const data = await res.json();
let gameArray = data.playedGames;
let gameInfo = [];
gameArray.map(game => {
gameInfo.push( game.teams[1].name + " VS " + game.teams[2].name);   
})
console.log(gameInfo);

最新更新