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.

Frank
  • 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 – Prabhu Murthy Aug 27 '14 at 14:19

1 Answers1

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.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • Or one could use OP's original structure and rely on the despised `eval` function: `alert(Number(eval(window.bar)));` – Ted Hopp Aug 27 '14 at 14:22
  • 1
    @TedHopp: The what? Sorry, never heard of it. ;-D – T.J. Crowder Aug 27 '14 at 14:23
  • Thank you @TedHopp, that answers my question. I appreciate the other answers as they give me some further clarification on better ways to program. – Frank Aug 27 '14 at 14:31