OStack程序员社区-中国程序员成长平台

标题: "Variable" variables in JavaScript [打印本页]

作者: 菜鸟教程小白    时间: 2022-4-10 16:06
标题: "Variable" variables in JavaScript

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?



Best Answer-推荐答案


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 classes.

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