如何展示从Rapid API获取的NFL周赛程数组数据?
解决Rapid API获取NFL赛程数据时的数组索引定位问题
我尝试通过Rapid API获取NFL周赛程数据,读取展示时遇到问题。API返回数组结构数据,但用索引(如0、1、2)引用数组内数据时出现无法定位的错误。
初始代码
const options = { method: 'GET', headers: { 'X-RapidAPI-Key': 'my-api-key', 'X-RapidAPI-Host': 'nfl-schedule.p.rapidapi.com' } }; fetch('https://nfl-schedule.p.rapidapi.com/v1/schedules', options) .then(function(response){ let data = response.json(); return data; }) .then(data => { console.log(data) const game = Array(16); for(i=0; i < game.length; i++){ const matchup = data[i].shortName; const gameDate = data[i].date; document.getElementById('matchup').innerText = matchup; document.getElementById('gameDate').innerText = gameDate; } }) .catch(err => console.error(err)); });
API返回的数据结构
{ message: 'NFL Scheduled games', data: [ { awayTeam: {name: 'Buccaneers', score: '0'}, date: "2022-11-27T18:00Z", homeTeam: {name: 'Browns', score: '0'}, name: "Tampa Bay Buccaneers at Cleveland Browns", shortName: "TB @ CLE", venue: "FirstEnergy Stadium" }, // 剩余15场比赛数据... ] }
问题分析与修复方案
- 核心错误:API返回的是包含
data数组的顶层对象,直接用data[i]访问数组元素是错误的,必须先访问data.data才能拿到赛程数组。 - 循环逻辑问题:手动创建
Array(16)无意义,直接遍历API返回的data.data数组更可靠,避免硬编码长度导致的不匹配。 - DOM更新问题:每次循环覆盖同一个DOM元素内容,最终只会显示最后一场比赛数据。需要创建新元素或使用容器批量渲染所有赛程。
修正后的代码
const options = { method: 'GET', headers: { 'X-RapidAPI-Key': 'my-api-key', 'X-RapidAPI-Host': 'nfl-schedule.p.rapidapi.com' } }; fetch('https://nfl-schedule.p.rapidapi.com/v1/schedules', options) .then(response => response.json()) .then(result => { // 拿到真正的赛程数组 const games = result.data; // 获取用于展示的容器 const scheduleContainer = document.getElementById('schedule-container'); games.forEach(game => { // 创建单个赛程的元素 const gameElement = document.createElement('div'); gameElement.innerHTML = ` <p>对阵: ${game.shortName}</p> <p>时间: ${game.date}</p> <hr> `; // 添加到容器中 scheduleContainer.appendChild(gameElement); }); }) .catch(err => console.error(err));
注意:需要在HTML中添加一个容器元素:
<div id="schedule-container"></div>
内容的提问来源于stack exchange,提问作者rklskls
相关产品推荐
相关产品推荐

