Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I refer to a variable using a string containing its name?

Tags:

Is there a way to refer to a Javascript variable with a string that contains its name?

example:

var myText = 'hello world!'; var someString = 'myText';  //how to output myText value using someString? 
like image 866
cardflopper Avatar asked Nov 02 '09 23:11

cardflopper


People also ask

How do you reference a variable in a string?

Place the character f before you start a string literal with single/double quotes as shown below. Now, we can reference variables inside this string. All we need to do is enclose the variables with curly braces {variable} and place this variable inside the string value, wherever required.

What is a string variable name?

A string variable is identified with a variable name that ends with the $ character. A string array variable has the $ character just before the left bracket that holds the array index. The variable name must begin with a letter and consist of 30 or fewer characters, including the $ character.

Can a variable contain a string?

A string is a type of value that can be stored in a variable.


2 Answers

You can use an eval to do it, though I try to avoid that sort of thing at all costs.

alert(eval(someString)); 

A better way, if you find yourself needing to do this, is to use a hash table.

var stuff = { myText: 'hello world!' }; var someString = 'myText'; alert( stuff[someString] ); 
like image 132
friedo Avatar answered Sep 29 '22 22:09

friedo


If that variable is on the global scope, you can use the bracket notation on the global object:

var myText = 'hello world!'; var someString = 'myText';  alert(window[someString]); 
like image 29
Christian C. Salvadó Avatar answered Sep 29 '22 21:09

Christian C. Salvadó