P粉4941519412023-08-25 16:40:34
If you desperately want to do this, you can try using eval():
var data = "testVariable"; eval("var temp_" + data + "=123;"); alert(temp_testVariable);
Or use window object:
var data = "testVariable"; window["temp_" + data] = 123; alert(window["temp_" + data]);
P粉8934570262023-08-25 11:49:08
tl;dr: Don't use eval
!
There is no single solution to this. It is possible to dynamically access some
global variables through the window , but this does not apply to local variables of a function. Global variables that do not become window
attributes are variables defined with let
and const
, and classes.
There is almost always a better solution than using mutable variables! Instead, you should look at data structures and choose the correct data structure for your problem.
If you have a fixed set of names like
// BAD - DON'T DO THIS!!! var foo = 42; var bar = 21; var key = 'foo'; console.log(eval(key));