You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将API返回的嵌套数组中NFL球队球员数据打印为表格行

解决NFL深度图表数据渲染错误及需求实现

问题说明

开发NFL数据库展示网站时,调用DepthCharts接口获取嵌套球员数据,出现Uncaught (in promise) ReferenceError: Defense is not defined错误。需要实现的功能是:根据页面team-select下拉框选中的球队,将该队Offense、Defense、SpecialTeams数组中所有球员的Name和Position字段,渲染到test-table表格中,每行对应一名球员,表格包含姓名和位置列。

错误根源

原代码存在多处逻辑错误:

  • 错误地将DOM元素teamSelect当作数据对象的属性使用,player.teamSelect.Defense.Name完全不符合数据结构
  • 没有筛选选中的球队,而是遍历所有球队数据
  • 未遍历Offense、Defense、SpecialTeams这三个嵌套数组里的球员条目

修正后的完整实现代码

HTML部分

<select name="team-select" id="team-select">
    <option value="0">ARI</option>
    <option value="1">ATL</option>
    <option value="2">BAL</option>
    <!-- 其他32支NFL球队选项 -->
</select>
<table id="test-table">
    <thead>
        <tr>
            <th>球员姓名</th>
            <th>位置</th>
        </tr>
    </thead>
    <tbody></tbody>
</table>

JavaScript部分

const depthCharts = "https://api.sportsdata.io/v3/nfl/scores/json/DepthCharts?key=";
const apiKey = "你的API密钥";
const testTable = document.getElementById("test-table").querySelector("tbody");
const teamSelect = document.getElementById("team-select");

// 获取并渲染选中球队的球员数据
async function renderTeamPlayers() {
    testTable.innerHTML = ""; // 清空表格内容
    const selectedTeamIndex = parseInt(teamSelect.value);

    try {
        const response = await fetch(depthCharts + apiKey);
        const allTeamsData = await response.json();
        const selectedTeam = allTeamsData[selectedTeamIndex];

        // 合并三个位置数组的球员数据
        const allPlayers = [
            ...selectedTeam.Offense,
            ...selectedTeam.Defense,
            ...selectedTeam.SpecialTeams
        ];

        // 遍历所有球员,生成表格行
        allPlayers.forEach(player => {
            const tr = document.createElement("tr");
            tr.innerHTML = `
                <td>${player.Name}</td>
                <td>${player.Position}</td>
            `;
            testTable.appendChild(tr);
        });
    } catch (error) {
        console.error("获取数据失败:", error);
    }
}

// 页面加载时默认渲染第一个球队数据,同时监听下拉框变化
window.addEventListener("load", renderTeamPlayers);
teamSelect.addEventListener("change", renderTeamPlayers);

关键修改点

  • 新增表格表头,明确列含义
  • 监听下拉框的change事件,选中球队后重新渲染数据
  • 根据下拉框的value值获取对应索引的球队数据
  • 使用扩展运算符...合并三个位置数组,统一处理所有球员
  • 遍历每个球员,正确渲染姓名和位置单元格
  • 添加try/catch捕获请求异常,提升代码健壮性

内容的提问来源于stack exchange,提问作者alexonwheels

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.21 02:35:55