0

I have an array of strings:

arr = ["bar","baz"]

and I have a few variables:

var bar = 'Hello';
var baz = 'bye';

using the array, how can I ouput:

hello
bye

I know how to loop, but, how can i use a string to refence a variable?

3
  • var arr = new Array(); arr["somevalue"] = "Hello"; var bar = arr["somevalue"]; Commented Feb 4, 2015 at 20:42
  • @DLeh no he means that he wants to access a variable by computing its name. That's not generally possible in JavaScript, though it is possible to access object properties via computed names (using the [ ] operator), and global variables are object properties (of the global object, window in a browser). Commented Feb 4, 2015 at 20:42
  • @DLeh Why would you new up an Array specifically, then use it as an associative container? Just use an object (or Map, where available). Commented Feb 4, 2015 at 20:43

2 Answers 2

3

The best option is to store the variables as properties within an object, and reference them that way:

var data = {
    bar: "Hello",
    baz: "Bye"
};

arr.forEach((key) => doStuff(data[key]));

Failing that, if you have access to some other scope (perhaps this during a method call), you can keep the variable as properties on the scope.

If you don't have any other scope available and no good options, all global variables are attached to the self (or window, when available) scope, so you can use the same sort of window[key] access.

Sign up to request clarification or add additional context in comments.

Comments

1

If the variables are global, you can access them by name using the property index of the window element:

arr = ["bar","baz"]

var bar = 'Hello';
var baz = 'bye';

arr.forEach(function(item) {
  alert(window[item]);
});

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.