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

如何提取API返回数组内对象的指定属性并展示到HTML页面

JoJo API 无法获取stand_type字段问题修复

问题根因

  • stand_type不是返回数组项的顶层字段,是嵌套在stand子对象内的属性,直接在顶层访问会返回undefined
  • 现有代码未做随机索引边界校验,若getRandomNumber()生成值超出数组长度范围,会取到空值触发后续访问报错
  • 未处理接口请求异常、部分无替身角色不存在stand字段的边界场景

修正后可运行代码

接口单条角色返回的结构中,替身相关字段全部嵌套在stand属性下,结构示例如下:

{
  "name": "角色名",
  "stand": {
    "stand_name": "替身名",
    "stand_type": "替身类型",
    "stand_power": "替身面板属性"
  }
}

完整实现(含字段提取、HTML渲染、异常处理):

// 生成合法范围内的随机索引,避免越界
function getRandomNumber(maxLen) {
  return Math.floor(Math.random() * maxLen);
}

async function getCharacter() {
  try {
    const response = await fetch('https://jojoapi.herokuapp.com/DiamondIsUnbreakable');
    if (!response.ok) throw new Error('接口请求异常');
    const characterList = await response.json();

    // 基于数组实际长度生成随机索引
    const randomIndex = getRandomNumber(characterList.length);
    const currentChar = characterList[randomIndex];
    
    // 提取目标字段,用可选链+空值合并处理无替身的边界情况
    const targetInfo = {
      characterName: currentChar.name,
      standName: currentChar.stand?.stand_name ?? '该角色无替身',
      standType: currentChar.stand?.stand_type ?? '该角色无替身',
      standPower: currentChar.stand?.stand_power ?? '无'
    };

    // 渲染到HTML页面,提前在页面准备id为char-container的容器即可
    const container = document.getElementById('char-container');
    container.innerHTML = `
      <h2>${targetInfo.characterName}</h2>
      <p>替身名称:${targetInfo.standName}</p>
      <p>*替身类型:${targetInfo.standType}*</p>
      <p>替身力量评级:${targetInfo.standPower}</p>
    `;
  } catch (err) {
    console.error('获取信息失败:', err);
  }
}

// 执行函数
getCharacter();

关键注意点

  • 访问嵌套属性时统一用?.可选链操作符,避免属性不存在时抛出JS错误中断脚本
  • 随机索引不要写死最大值,必须以接口实际返回的数组长度为基准生成,从根源避免越界
  • 异步请求必须加try/catch捕获异常,防止接口故障时页面脚本崩溃

内容的提问来源于stack exchange,提问作者Mirko Bubica Hundt

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.29 16:54:08