I know it's possible in PHP to have "variable" variables. For example,
$x = "variable";
$$x = "Hello, World!";
echo $variable; // Displays "Hello, World!"
Is it possible to refer to a variable by its name as a string in JavaScript? How would it be done?
tl;dr: Don't use eval
!
There is no single solution for this. It is possible to access some global variables dynamically via window
, but that doesn't work for variables local to a function. Global variables that do not become a property of window
are variables defined with let
and const
, and class
es.
There is almost always a better solution than using variable variables! Instead you should be looking at data structures and choose the right one for your problem.
If you have a fixed set of names, such as
// BAD - DON'T DO THIS!!!
var foo = 42;
var bar = 21;
var key = 'foo';
console.log(eval(key));
欢迎光临 OStack程序员社区-中国程序员成长平台 (http://ostack.cn/) | Powered by Discuz! X3.4 |