【问题标题】:Javascript - forEach is not a function APIJavascript - forEach 不是函数 API
【发布时间】:2021-03-16 16:06:32
【问题描述】:

我在 javascript 中使用 API,使用 fetch 获取数据并将其放入表中,但我不断收到类型错误,指出 .forEach 不是函数。

下面我粘贴了我的 HTML 和 JavaScript。

HTML:

    <table>
      <thead>
        <tr>
          <th>Player Name</th>
          <th>Position</th>
          <th>Nationality</th>
        </tr>
      </thead>
      <tbody></tbody>
    </table>

JavaScript:

// Personal API Key
var apiKey = '⟨the key⟩';

function requestLeagueTable() {
  fetch('https://api.football-data.org/v2/competitions/PL/scorers', {
      headers: {
        'X-Auth-Token': apiKey,
      }
    })
    .then((response) => response.json())
    .then((data) => {
      console.log('Data :', data);
      createTable(data);
    })
    .catch((error) => {
      console.error('Error:', error);
    });
}

// create the table
function createTable(data) {
  var players = data.scorers[0].player;
  var teams = data.scorers[0].team;
  var goals = data.scorers[0].numberOfGoals;

  players.forEach(createTeam);
  teams.forEach(createTeam);
  goals.forEach(createTeam);
}

function createTeam(player, team, goal) {
  // create an element for each element
  var teamElement = document.createElement("tr");

  // add each individual piece of data
  addTeamData(player.name, teamElement);
  addTeamData(team.name, teamElement);
  addTeamData(player.position, teamElement);
  addTeamData(player.nationality, teamElement);
  addTeamData(goal, teamElement);

  // add the team to the page
  var tableElement = document.querySelector("tbody");
  tableElement.appendChild(teamElement);
}

// add each individual piece of team data
function addTeamData(data, element) {
  var td = document.createElement("td");
  td.textContent = data;
  element.appendChild(td);
}

// update on page load
requestLeagueTable();

如果你能帮助我,将是非常有益的。

非常感谢

【问题讨论】:

  • playersteamsgoals 可能是 undefined
  • ^... 或者它们不是数组。
  • @Teemu 我已经添加了控制台数据的图像
  • 图片告诉playersteams是一个对象,goals是一个数字。另外,forEach的回调函数获取当前迭代通过的值的值、索引和数组,它不会做你期望它做的事情。
  • data.scorers.forEach(({player, team, numberOfGoals}) =&gt; createTeam(player, team, numberOfGoals));。或者,.forEach(createTeam),将函数头更改为function createTeam({player, team, numberOfGoals}),并相应地调整变量。 data.scorers 是您要迭代的数组。请阅读documentation

标签: javascript html api foreach html-table


【解决方案1】:

你试图做一个 forEach :

 var goals = data.scorers[0].numberOfGoals;

所以goals不是一个数组,所以你不能对它做forEach。

【讨论】:

  • 我怎样才能让它工作并在表格中显示数据?
  • 您想要显示的值。请验证答案。
  • 我想在表格中显示球员、球队和进球
  • 对所有足球进行循环,然后在其中获取它们的数据。
  • 你的意思是这样的:``` var player = data.scorers.player; for (var i = 0; i
【解决方案2】:

我的做法是这样的:

function createTable(data) {
data.scorers.forEach(({player, team, numberOfGoals}) => createTeam(player, team, numberOfGoals));
}

【讨论】:

  • 这是答案吗?
  • 是的,这是一个答案
猜你喜欢
  • 2018-03-02
  • 2022-08-18
  • 1970-01-01
  • 2016-06-28
  • 1970-01-01
  • 2020-08-07
  • 1970-01-01
  • 2017-04-03
  • 2017-04-06
相关资源
最近更新 更多