Question : JavaScript Variable Variable

Hi All,

How do i use a variable name to look up another variable value?

var variable1 = variable2 + 'random_id';


This is for a Media Centre, so it has a limited JavaScript library;
http://www.networkedmediatank.com/wiki/index.php/Javascript_on_NMT

Answer : JavaScript Variable Variable

"eval" is evil - better to use a bit more structure.

Create a JSON object that holds the "name,value" pairs, then reference that instead.

1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
var v = {
    'variable_1':'123',
    'variable_2':'246',
    'variable_3':'3.1415'
};

// You can add variables like this:

v['var_name' + random_id] = 'whatever';

// You access the variables like this:

var var_1 = v.variable_1;
var var_rnd = v['var_name' + random_id];
Random Solutions  
 
programming4us programming4us