汇率计算器显示NaN问题求助:附JS代码与API响应数据
货币转换计算器显示NaN问题排查求助
我正在开发一款货币转换计算器,但计算结果始终显示NaN,尝试多种方法仍未解决。以下是我的JavaScript代码、页面截图及API返回的响应数据,恳请帮忙排查问题:
JavaScript代码
const dropList = document.querySelectorAll("form select"), fromCurrency = document.querySelector(".from select"), toCurrency = document.querySelector(".to select"), getButton = document.querySelector("form button"); for (let i = 0; i < dropList.length; i++) { for (let currency_code in country_list) { let selected = i == 0 ? currency_code == "USD" ? "selected" : "" : currency_code == "NPR" ? "selected" : ""; let optionTag = `<option value="${currency_code}" ${selected}>${currency_code}</option>`; dropList[i].insertAdjacentHTML("beforeend", optionTag); } dropList[i].addEventListener("change", (e) => { loadFlag(e.target); }); } function loadFlag(element) { for (let code in country_list) { if (code == element.value) { let imgTag = element.parentElement.querySelector("img"); imgTag.src = `https://flagcdn.com/48x36/${country_list[ code ].toLowerCase()}.png`; } } } window.addEventListener("load", () => { getExchangeRate(); }); getButton.addEventListener("click", (e) => { e.preventDefault(); getExchangeRate(); }); const exchangeIcon = document.querySelector("form .icon"); exchangeIcon.addEventListener("click", () => { let tempCode = fromCurrency.value; fromCurrency.value = toCurrency.value; toCurrency.value = tempCode; loadFlag(fromCurrency); loadFlag(toCurrency); getExchangeRate(); }); function getExchangeRate() { const amount = document.querySelector("form input"); const exchangeRateTxt = document.querySelector("form .exchange-rate"); let amountVal = amount.value; amountVal = parseFloat(amountVal); if (amountVal == "" || amountVal == "0") { amount.value = "1"; amountVal = 1; } exchangeRateTxt.innerText = "Getting exchange rate..."; let url = `https://api.fastforex.io/convert?from=${fromCurrency.value}&to=${toCurrency.value}&amount=${amountVal}&api_key=xxx-xxx-xxx`; // api key on p fetch(url) .then((response) => response.json()) .then((result) => { let exchangeRate = result.rate; let totalExRate = (amountVal * exchangeRate).toFixed(2); exchangeRateTxt.innerText = `${amountVal} ${fromCurrency.value} = ${totalExRate} ${toCurrency.value}`; }) .catch(() => { exchangeRateTxt.innerText = "Something went wrong"; }); }
API响应数据
{ "base": "USD", "amount": 1, "result": { "AED": 3.67, "rate": 3.67189 }, "ms": 5 }
页面截图

内容的提问来源于stack exchange,提问作者John
相关产品推荐
相关产品推荐

