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

如何优化JS代码避免重复将API值赋值给不同元素?

优化重复的汇率赋值代码

我是JavaScript新手,正在尝试从API服务器获取数据,但如你所见,每个货币元素都被赋值了不同的币种数值。我也曾尝试对currency对象使用for循环,但仍无法避免这种重复操作。

原代码:

const container=document.querySelector(".scoll_display");
const currency=container.querySelectorAll(".Exchange_rate");

async function getExchangePrice() {
    const options = {
      method: "GET",
      headers: { "x-cg-demo-api-key": "CG-NhdhrCZRnCSqdjMyf3XUu9k4" },
    };
  
    try {
        const response1= await fetch("https://api.coingecko.com/api/v3/exchange_rates", options);
        const data1 = await response1.json();
        
        currency[1].innerHTML=`(ETH) ${data1.rates.eth.value}`;
        currency[2].innerHTML=`(LTC) ${data1.rates.ltc.value}`;
        currency[3].innerHTML=`(BCH) ${data1.rates.bch.value}`;
        currency[4].innerHTML=`(BNB) ${data1.rates.bnb.value}`;
        currency[5].innerHTML=`(XLM) ${data1.rates.xlm.value}`;
        currency[6].innerHTML=`(DOT) ${data1.rates.dot.value}`;
        currency[7].innerHTML=`(₹) ${data1.rates.inr.value}`;
        currency[8].innerHTML=`(¥) ${data1.rates.jpy.value}`;
        currency[9].innerHTML=`(μBTC) ${data1.rates.bits.value}`;
        currency[10].innerHTML=`(£) ${data1.rates.gbp.value}`; 
      
    } catch (error) {
      console.error(error);
    }
  }
  
  getExchangePrice();

解决方案

把需要处理的币种信息统一整理成配置数组,通过遍历数组完成赋值,彻底消除重复代码:

const container = document.querySelector(".scoll_display");
const currencyElements = container.querySelectorAll(".Exchange_rate");

// 统一管理币种配置:[显示符号, API返回的键名]
const currencyConfigs = [
  ["(ETH)", "eth"],
  ["(LTC)", "ltc"],
  ["(BCH)", "bch"],
  ["(BNB)", "bnb"],
  ["(XLM)", "xlm"],
  ["(DOT)", "dot"],
  ["(₹)", "inr"],
  ["(¥)", "jpy"],
  ["(μBTC)", "bits"],
  ["(£)", "gbp"]
];

async function getExchangePrice() {
  const options = {
    method: "GET",
    headers: { "x-cg-demo-api-key": "CG-NhdhrCZRnCSqdjMyf3XUu9k4" },
  };

  try {
    const response = await fetch("https://api.coingecko.com/api/v3/exchange_rates", options);
    const data = await response.json();
    
    // 遍历配置数组完成赋值
    currencyConfigs.forEach(([symbol, key], index) => {
      // 原代码从currency[1]开始使用,所以索引+1
      const targetElement = currencyElements[index + 1];
      if (targetElement) {
        targetElement.innerHTML = `${symbol} ${data.rates[key].value}`;
      }
    });
  } catch (error) {
    console.error(error);
  }
}

getExchangePrice();

说明

  • 用currencyConfigs数组集中管理所有币种的显示符号和API键名,后续新增/修改币种只需调整这个数组
  • 用forEach遍历数组,自动匹配对应的DOM元素,避免重复写innerHTML赋值语句
  • 增加了元素存在性判断,防止因DOM元素数量不足导致报错

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 09:25:34