所以我对 JS 有点陌生,我一直在尝试从 API 服务器获取数据,但正如你所看到的,每个货币元素都分配给不同的硬币值。我也尝试过对货币对象使用 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();
在这种情况下您可以使用
forEach
以避免重复:
const currencyTypes=['eth','ltc','bth'....etc] ;
currencyTypes.forEach((type, index) => {
currency[index + 1].innerHTML = `(${type.toUpperCase()}) ${data.rates[type].value}`;
});