以下是一个使用JavaScript进行简单汇率换算的示例代码:
// 假设我们有从美元到人民币的汇率
const exchangeRateUSDToCNY = 6.5;
function convertCurrency(amount, fromCurrency, toCurrency) {
if (fromCurrency === 'USD' && toCurrency === 'CNY') {
return amount * exchangeRateUSDToCNY;
} else if (fromCurrency === 'CNY' && toCurrency === 'USD') {
return amount / exchangeRateUSDToCNY;
} else {
throw new Error('暂不支持的货币类型转换');
}
}
// 示例用法
const usdAmount = 10;
const cnyAmount = convertCurrency(usdAmount, 'USD', 'CNY');
console.log(`${usdAmount} 美元换算成人民币为 ${cnyAmount} 元`);
const newUsdAmount = convertCurrency(cnyAmount, 'CNY', 'USD');
console.log(`${cnyAmount} 元人民币换算成美元为 ${newUsdAmount} 美元`);
一、基础概念
exchangeRateUSDToCNY = 6.5
表示1美元可以兑换6.5元人民币。convertCurrency
函数就是用于根据给定的金额、源货币和目标货币进行换算的函数。二、优势
三、类型(从功能角度)
四、应用场景
五、可能遇到的问题及解决方法
fetch
函数(在浏览器环境下)或者axios
库(在Node.js环境下)来获取外部数据。领取专属 10元无门槛券
手把手带您无忧上云