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

使用Fetch获取API数据报错:globalInfo.map is not a function

解决“globalInfo.map is not a function”报错问题

错误根源

你调用map()的globalInfo是单个对象,而非数组。从你提供的API返回数据可以看到,接口直接返回了包含market_cap_usd、volume_24h_usd等字段的单一对象,而map()是数组专属方法,对象没有这个方法,因此触发类型错误。

原代码额外问题

  1. 字段取值错误:market_cap_usd.info和volume_24h_usd.info写法错误,应该直接从globalInfo对象中读取对应字段
  2. 未处理请求异常:缺少catch()捕获网络请求或数据解析时的错误

修正后的代码

场景1:仅提取单个对象的指定字段

如果只需要获取market_cap_usd和volume_24h_usd的值,直接操作对象即可,无需使用map():

fetch('https://coinpaprika1.p.rapidapi.com/global', target)
  .then(response => {
    // 先判断请求是否成功
    if (!response.ok) {
      throw new Error(`请求失败:${response.status}`);
    }
    return response.json();
  })
  .then((globalInfo) => {
    const infos = {
      mcap: globalInfo.market_cap_usd,
      volume: globalInfo.volume_24h_usd
    };
    // 这里可以添加渲染逻辑,比如将infos展示到页面
    console.log(infos);
  })
  .catch(error => {
    console.error('数据获取失败:', error);
  });

场景2:需要将结果转为数组(适配后续数组逻辑)

如果后续业务逻辑必须使用数组格式,可以把单个对象包装成数组后再处理:

fetch('https://coinpaprika1.p.rapidapi.com/global', target)
  .then(response => {
    if (!response.ok) {
      throw new Error(`请求失败:${response.status}`);
    }
    return response.json();
  })
  .then((globalInfo) => {
    // 将单个对象转为数组,再用map处理(适合后续需要批量处理多个对象的场景)
    const infos = [globalInfo].map(item => ({
      mcap: item.market_cap_usd,
      volume: item.volume_24h_usd
    }));
    console.log(infos);
  })
  .catch(error => {
    console.error('数据获取失败:', error);
  });

关键注意事项

  • 调用API前务必确认返回数据的结构(对象/数组),再选择对应的处理方法
  • 数组方法(map()/filter()/forEach()等)不能直接用于对象
  • 必须添加catch()处理Promise异常,避免出现未捕获的Promise错误

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 10:33:28