0

I need to assign a variable name from a second variable, then alert the value of the first variable in JavaScript.

Below is an example of what I am trying to achieve.

window.foo=0;
window.bar="window.foo";

//want to set an alert for window.bar in a way that returns 0
alert(window.bar); //returns window.foo
alert(Number(window.bar)); //returns window.NaN

In the example above, I am looking to alert the value 0. How would that be accomplished? Thank you.

1
  • 2
    remove the double quotes around window.foo. window.bar = window.foo.Number(0) does not make any sense. what are you trying to do Commented Aug 27, 2014 at 14:19

1 Answer 1

1

If they're global variables (as those are), you can simply use "foo" rather than "window.foo" when looking it up on window:

var name = "foo";
window.foo = 0;
alert(Number(window[name])); // 0;

But global variables are a Bad Thing(tm).

To do this without globals, use your own object:

var name = "foo";
var obj = {};
obj.foo = 0;
alert(Number(obj[name])); // 0;

Both of the above work because in JavaScript, you can refer to an object property either with dot notation and a literal (obj.foo), or with bracketed notation and a string (obj["foo"]), and in the latter case, the string can be the result of any expression, including a variable lookup.

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

3 Comments

Or one could use OP's original structure and rely on the despised eval function: alert(Number(eval(window.bar)));
@TedHopp: The what? Sorry, never heard of it. ;-D
Thank you @TedHopp, that answers my question. I appreciate the other answers as they give me some further clarification on better ways to program.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.