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

如何在Ball Don't Lie API数组中展示所有球员姓名及其他数据

问题:无法通过Ball Don't Lie API展示所有球员数据

我正在使用Ball Don't Lie API完成首个项目,尝试搭建ESPN风格的着陆页,调用接口为https://www.balldontlie.io/api/v1/players。目前使用JavaScript开发,仅能通过data.data[0]显示单个球员姓名,尝试过.map方法和循环仍无法实现展示所有球员姓名及其他数据,已卡壳数日。附上现有代码:

async function getPlayers() {
    const response = await fetch ('https://www.balldontlie.io/api/v1/players');
    const data = await response.json();
    const players = data.data;
    console.log(players);
    displayPlayer(players);
}

function displayPlayer(players) {
    const scores = document.getElementById('scores');
    scores.innerHTML = `
    ${players.first_name} ${players.last_name}`;
}

getPlayers()

我试过.map和循环,但始终没搞懂如何实现球员展示,原代码可能存在问题,也没找到简单JavaScript实现的相关教程。


解决方案

问题根源

原代码的核心问题是:players是一个数组,直接访问players.first_name是在数组对象上查找该属性,而数组本身没有这个属性——数组里的每一个元素才是包含first_name、last_name的球员对象,因此必须遍历数组处理每个球员。

方法1:使用.map生成HTML字符串

通过.map遍历球员数组,为每个球员生成对应的HTML片段,最后用.join('')把数组转为字符串,赋值给目标元素的innerHTML:

async function getPlayers() {
    const response = await fetch ('https://www.balldontlie.io/api/v1/players');
    const data = await response.json();
    const players = data.data;
    console.log(players);
    displayPlayer(players);
}

function displayPlayer(players) {
    const scores = document.getElementById('scores');
    // 遍历每个球员,生成HTML片段
    const playerListHtml = players.map(player => `
        <div class="player-item">
            <h3>${player.first_name} ${player.last_name}</h3>
            <p>所属球队:${player.team.full_name}</p>
            <p>位置:${player.position || '未指定'}</p>
        </div>
    `).join(''); // 将数组转为字符串
    scores.innerHTML = playerListHtml;
}

getPlayers()

方法2:使用for...of循环拼接HTML

如果对.map不太熟悉,也可以用基础的for...of循环逐个拼接HTML内容:

async function getPlayers() {
    const response = await fetch ('https://www.balldontlie.io/api/v1/players');
    const data = await response.json();
    const players = data.data;
    console.log(players);
    displayPlayer(players);
}

function displayPlayer(players) {
    const scores = document.getElementById('scores');
    let playerListHtml = '';
    // 循环遍历每个球员
    for (const player of players) {
        playerListHtml += `
            <div class="player-item">
                <h3>${player.first_name} ${player.last_name}</h3>
                <p>所属球队:${player.team.full_name}</p>
                <p>位置:${player.position || '未指定'}</p>
            </div>
        `;
    }
    scores.innerHTML = playerListHtml;
}

getPlayers()

额外提示

  • 可以给.player-item类添加CSS样式,模拟ESPN的卡片式布局
  • 接口返回的球员数据还包含更多字段(如身高、体重),可以根据需求添加到HTML中
  • 如果需要分页展示,可以查看API文档中的分页参数(page、per_page)实现加载更多功能

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 15:35:44