运行以下语句时,控制台选项卡显示以下错误
在控制台中运行的命令convert(100, 'CAD', 'USD')
运行上述转换状态请求后控制台显示错误
Promise rejecion TypeError时暂停:无法读取未定义的属性 在代码64行,这里`` const rate = ratesByBase[from].rates[to];
以下是我的完整代码库
let currencies = {
AUD: 'Australian Dollar',
BGN: 'Bulgarian Lev',
BRL: 'Brazilian Real',
CAD: 'Canadian Dollar',
CHF: 'Swiss Franc',
CNY: 'Chinese Yuan',
CZK: 'Czech Republic Koruna',
DKK: 'Danish Krone',
GBP: 'British Pound Sterling',
HKD: 'Hong Kong Dollar',
HRK: 'Croatian Kuna',
HUF: 'Hungarian Forint',
IDR: 'Indonesian Rupiah',
ILS: 'Israeli New Sheqel',
INR: 'Indian Rupee',
JPY: 'Japanese Yen',
KRW: 'South Korean Won',
MXN: 'Mexican Peso',
MYR: 'Malaysian Ringgit'
}
const fromSelect = document.querySelector('[name="from_currency"]');
const toSelect = document.querySelector('[name="to_currency"]');
const fromInput = document.querySelector('[name="from_amount"]');
let myHeaders = new Headers();
myHeaders.append("apikey", "QC9I9O0LPCFUfStGMD1h5CKcWN4Aehrk");
let requestOptions = {
method: 'GET',
redirect: 'follow',
headers: myHeaders
};
const endpoint = "https://api.apilayer.com/currency_data/live";
let ratesByBase = {};
function generateOptions(options) {
return Object.entries(options)
.map(([currencyCode, currencyName]) =>
`<option value="${currencyCode}">${currencyCode} - ${currencyName}</option>`)
.join("");
}
async function fetchRates(base = "USD") {
const res = await fetch(`${endpoint}?base=${base}`, requestOptions);
const rates = await res.json();
return rates;
}
async function convert(amount, from, to) {
// first check if we even have the rates to convert from that currency
if (!ratesByBase[from]) {
console.log(`Oh no! we don't have ${from} to convert it ${to}, so let 's go get it`);
const rates = await fetchRates(from);
console.log(rates);
// store them for next time
ratesByBase[from] = rates;
}
const rate = ratesByBase[from].rates[to];
const convertedAmount = rate * amount;
console.log('${amount} ${from} is ${convertedAmount} in ${to}');
return convertedAmount;
}
const optionsHTML = generateOptions(currencies);
// populate the options elements
fromSelect.innerHTML = optionsHTML;
toSelect.innerHTML = optionsHTML;
2条答案
按热度按时间w1e3prcc1#
我完成了所有的步骤,但我不会从这个提供的步骤获得奖励做一个0.60$最低存款用户必须发挥保持奖励新用户只有我会按照这个步骤,我做一个0.60$存款和发挥,我是一个新用户,请检查快,给予价格的钱
iswrvxsc2#
“ratesByBase[from]”可能未定义。
使用typescript:const rate = ratesByBase[from]?.rates[to];
使用JavaScript:const rate = ratesByBase[from]?ratesByBase[from].rates[to]:0的整数;