2017-11-15 2 views
0

이것은 JS 라이브러리 (PLN, EUR 등)의 마지막 값을 기반으로 JS 라이브러리에서 환율을 가져 오는 간단한 통화 변환기 스크립트입니다. ->인수의 값을 사용하여 객체 속성에 액세스

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

+1

'Currency.rates.PLN' 무엇인가? – gurvinder372

+0

JS 라이브러리에서 환율을 반환합니다. 값은 약 0.27입니다. –

+0

'Currency.rates'객체에 무엇이 포함되어 있는지 알지 못해도별로 도움이되지 않지만'var currencyRateUSDPLN = Currency.rates.to ;''Currency.rates.PLN; '을 함수에 전달하는 것처럼''var currencyRateUSDPLN = to;'가 되겠습니까? – George

답변

3

나는 당신이 물어하려는 질문이 객체의 속성에 액세스 인수의 값을 사용할 수있는 방법입니다 있으리라 믿고있어. 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'); 
} 
+0

와우! 놀랄 만한! 이제 나는 그가 의미하는 바를 이해할 수있다. – skyboyer

+0

감사! 나는 이것을 정확히 의미했다. 나는 당신의 제안에 대한 질문 제목을 바꿀 것이다. 문제 해결됨! –

1

이 작업을 수행하는 방법은 대괄호 ([])를 통해 to 값을 보간하는 것입니다

당신이 사용하는 브라켓 표기법을 할 수 있습니다. 그래서 대신 함수에 문자열을 전달하고이를 보간의

Currency.rates[to] 

은 또는, 당신은 단지 직접 환율 참조를 전달할 수 :

function convertCurrency (amount, to) { 
    console.log((amount/to).toFixed(2) + ' PLN'); 
} 

convertCurrency(34.56, Currency.rates.PLN) 
관련 문제