0

I want to access the variable FR[0]. The variable country is "FR". I thought this would do it:

console.log("eval country: " + eval("country"));
console.log("fr0: " + FR[0]);
 console.log("eval country0: " + eval("country")[0];  

The output is:

  eval country: FR
     fr0: http://www.example.co.uk/
    eval country0: F

What am I doing wrong?

Edit: the clarify: the country variable changes. Sometimes it is FR sometimes it is UK etc etc. I want to it access the appropriate variable based on the string that country contains.

3
  • 4
    #1 Don't use eval() needlessly (this is one of those times). #2, what do FR and country look like? Commented Nov 2, 2017 at 17:47
  • eval(country) would do that, however you could simply do country = FR so theres no need to use evil eval at all Commented Nov 2, 2017 at 17:50
  • It is really unclear what you are trying to do. What's the expected output here? Seems like it's doing what it should. Commented Nov 2, 2017 at 17:52

1 Answer 1

1

I think to answer your specific question, you'd have to do something like:

eval(country + '[0]')

But this is terrible practice because if the string was some malicious JS, then it would be evaluated and bad things would/could happen. It would be better to just have an object store that data instead of having them in separate variables:

var myData = {
  "FR": ['http://example.co.fr', 'adf', 'asdf'],
  "UK": ['http://example.co.uk', 'asdf', 'asdf']
};

and access it like this:

myData[country][0]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.