0

I have these imaginary exchange rates:

var eur2usd = '0.90';
var eur2gbp = '1.20';
var usd2eur = '1.10';
var usd2gbp = '1.28';
var gbp2eur = '0.85';
var gbp2usd = '0.78';

(the values are assigned to the variables dynamically -and that works fine)

Then I have 2 more variables:

var firstPart = 'usd'; //also assigned dynamically (can be usd, eur or gbp)
var secondPart = 'eur'; //also assigned dynamically (can be usd, eur or gbp)

When I do:

alert(firstPart+'2'+secondPart);

the result I get is "usd2eur".

So far I managed to construct and alert the name of the variable, but I would like to get its actual value as set before (which in this case is: "1.10") and not it's name.

Any ideas?

Theo Orphanos
  • 1,417
  • 1
  • 19
  • 27
  • 1
    if variables are global, `alert(window[firstPart+'2'+secondPart])`. bad practice though. – Aᴍɪʀ Jan 19 '17 at 23:52
  • 1
    Using variable variables is almost always a bad idea. Use a map! – Felix Kling Jan 19 '17 at 23:55
  • @FelixKling I know is bad idea, but this particular feature will be used in a controlled environment by one or two logged-in administrators. However, I didn't know about the map. Can you provide an example or a resource? (I will also check the answers to the other "duplicate" question in case map is mentioned there) – Theo Orphanos Jan 19 '17 at 23:59
  • 2
    A map is simply a data structure that *maps* a name to a value. You can use an object as a map. E.g. you could create `var exchange = {eur: {usd: 0.9, gbp: 1.2}};` and then you can access the rate via `exchange[firstPart][secondPart]`. – Felix Kling Jan 20 '17 at 00:05
  • I ended up using namespace: var myNamespace = {eur2eur: '1.00', eur2usd: '1.12', eur2gbp: '1.23', ...etc}; And then to call the variable simply do: alert(myNamespace[firstPart+'2'+secondPart]); I just mentioned my solution hoping it could help someone else too... – Theo Orphanos Jan 22 '17 at 04:15

0 Answers0