繁体   English   中英

如何获取从 api 返回的所有值? Javascript

[英]How can I get all values returned from 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;






});

创建空数组或 object 而不是字符串。 我是关于变量游戏信息的。 并且在每次交互中你必须添加新值(例如 gameInfo.push(value) 如果它将是数组)。 因此您将获得包含有关每个项目的信息的数组。 你将能够将它用于你的目标

在你的 vaiant 中,你在每次交互时重写 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")));

如前所述,您每次都在 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;
 });

 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);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM