If the variables are global , then you can use
var y = window["variable_" + x];
for reading or
window["variable_" + x] = y;
to write them dynamically.
It is best to use an object to store them instead of using separate variables ...
var data = { variable_1: null, variable_2: null }; ... y = data["variable_" + x];
Javascript can also use eval
to access dynamic variables, surprisingly even local variables.
function foo(s) { var x = 12; return eval(s); } console.log(foo("x"));
and even more surprisingly, it allows you to dynamically create new local variables ...
var y = 42; function foo(s) { var x = 1; eval(s); return y; // may be global y or a local y defined by code in s } foo("x") // returns 42 foo("var y = 99") // returns 99 (but global y is not changed!)
but these uses of eval
should be considered a mistake rather than a function, and should be avoided (they also make the code impossible in principle to optimize or understand “just don't do it”).
source share