Refer to variable based on another variable

- 1 answer

Ad

If I had the following code:

var number = 3;

var value1 = 22;
var value2 = 50;
var value3 = 63;

You can see that number = 3 and so from this I would like to get the value of value3 and say if number = 2; I would like to get the value of value2.

Is this possible? Thanks.

Ad

Answer

Ad

I would use an array instead, if possible.

var values = [22,50,63],
number = 2;

console.log(values[number]);
// 63

If this is not the case then the only other way I can think of is using eval which has some risks associated with it.

Try:

var number = 3;

var value1 = 22;
var value2 = 50;
var value3 = 63;

eval('value' + number);
// 63

If they are global objects then they may already be available as a key on the window object:

window['value3']
// 63

Which means you can concat the string in the key name:

window['value' + num]
// 63
Ad
source: stackoverflow.com
Ad