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

无法正确遍历CoinRankingAPI返回的JSON对象问题求助

问题解决:CoinRankingAPI遍历币种价格时的“不可迭代对象”错误

核心错误原因

  1. URL参数构造错误:你的API密钥没有以正确的参数名传递,CoinRankingAPI要求密钥通过api_key查询参数传递,原代码直接拼接密钥会导致请求无效或响应结构异常。
  2. 响应结构解析错误:API返回的data是一个对象,而非可迭代数组,真正的币种列表在data.coins字段中,直接遍历data会触发“不可迭代”错误。

修正后的代码

const apiKey = 'XXXX';
const url = `https://api.coinranking.com/v2/coins?api_key=${apiKey}`;

function loadPrices() {
  // 用fetch替代XMLHttpRequest,代码更简洁
  fetch(url)
    .then(response => response.json())
    .then(result => {
      // 正确获取可迭代的币种数组
      const coinsList = result.data.coins;
      const container = document.getElementById("hello");
      // 先拼接所有内容再一次性插入DOM,提升性能
      let priceHtml = '';
      coinsList.forEach(coin => {
        priceHtml += `<br />${coin.price}`;
      });
      container.innerHTML = priceHtml;
    })
    .catch(error => {
      console.error('请求出错:', error);
    });
}

// 调用函数加载数据
loadPrices();

关键修正点说明

  • URL修正:使用模板字符串拼接api_key参数,确保API能正确识别密钥。
  • 响应解析修正:从result.data.coins获取可迭代的币种数组,而非直接使用result.data。
  • DOM操作优化:先拼接HTML字符串再一次性赋值给innerHTML,避免频繁修改DOM造成性能损耗。
  • 错误处理:添加catch块捕获请求或解析过程中的错误,方便调试。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 04:27:31