这是一个简单的货币转换器脚本,它从 JS 库获取货币汇率 - 它基于 JSON 链接中的最后一个值(PLN、欧元等)->
var priceAmount = amount;
var currencyRateUSDPLN = Currency.rates.PLN;
我知道我无法将函数参数直接传递给Currency.rates.PLN,实现此功能的最短方法是什么?
function convertCurrency (amount, to) {
var priceAmount = amount;
// here I want to pass 'to' argument (EUR, PLN for example)
var currencyRateUSDPLN = Currency.rates.to;
var pricePLN = ( priceAmount / currencyRateUSDPLN ).toFixed(2);
console.log(pricePLN + ' PLN');
}
货币对象包含 -> link
最佳答案
我假设您想问的问题是如何使用参数的值来访问对象属性。
您可以使用括号表示法来做到这一点:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Property_Accessors
function convertCurrency (amount, to) {
var priceAmount = amount;
// here I want to pass 'to' argument (EUR, PLN for example)
var currencyRateUSDPLN = Currency.rates[to];
// If 'to' argument passed in is "EUR" then this
// will resolve to Currency.rates.EUR
var pricePLN = ( priceAmount / currencyRateUSDPLN ).toFixed(2);
console.log(pricePLN + ' PLN');
}
关于javascript - 使用参数的值来访问对象属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47304302/