是否有与 PHP 的“变量”等效的 JavaScript?
我知道 PHP 中可能有 变量 变量,其中人们可以通过存储在另一个变量中的名称来访问一个变量。例如,
$x = "variable";
$$x = "Hello, World!";
echo $variable; // Displays "Hello, World!"
是否可以在 JavaScript 中执行相同的操作?该怎么做呢?
I know it's possible in PHP to have variable variables, where one can access a variable by a name stored in another variable. For example,
$x = "variable";
$x = "Hello, World!";
echo $variable; // Displays "Hello, World!"
Is it possible to do the same in JavaScript? How would it be done?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(9)
tl;dr:不要使用< code>eval!
对于这个问题没有单一的解决方案。可以通过
窗口
动态访问一些全局变量,但这不适用于函数的本地变量。 不成为window
属性的全局变量是用let
和const
定义的变量,以及类。
几乎总是有比使用可变变量更好的解决方案! 相反,您应该查看数据结构 并选择适合您问题的选项。
如果您有一组固定的名称,例如
将这些名称/值存储为对象的属性,并使用括号表示法动态查找它们:
在 ES2015+ 中,使用简洁的属性表示法对现有变量执行此操作甚至更容易:
如果您有“连续”编号的变量,例如
那么你应该使用数组来代替,并简单地使用索引来访问相应的值:
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 ofwindow
are variables defined withlet
andconst
, andclass
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
store those names/values as properties of an object and use bracket notation to look them up dynamically:
In ES2015+ it's even easier to do this for existing variables using concise property notation:
If you have "consecutively" numbered variables, such as
then you should be using an array instead and simply use the index to access the corresponding value:
如果您迫切希望这样做,您可以尝试使用 eval():
或使用 window 对象:
If you are desperate to do this you can either try using eval():
Or using the window object:
要仅使用字符串引用 JavaScript 中的变量,您可以使用
You can set and reference Variables, and objects in Variables so。
To reference a variable in JavaScript with only a string, you can use
You can set and reference variables, and objects in variables too.
您可以使用全局
window
对象,或this
:window
:或使用点:
This:
或使用点
一个现实生活中的例子:
You can use the global
window
object, orthis
:window
:Or using dot:
This:
or using dot
A real-life example:
与 PHP 不同,JavaScript 不提供对全局数组(其中包含对当前声明的所有变量名称的引用)的访问。因此,JavaScript 不提供对变量的本机支持。但是,只要将所有变量定义为数组或对象的一部分,您就可以模拟此功能。这将为您创建一个全局数组。例如,不要像这样在全局作用域中声明变量
hello
:让我们将其封装在一个对象内。我们将调用该对象
vv
(变量变量):现在我们可以通过变量的索引引用该变量,并且由于可以使用变量提供数组索引,因此我们实际上正在使用变量变量:
问题的答案
让我们将其应用到您在原始问题中提供的代码:
实际用途
虽然前面的代码可能显得非常繁琐和不切实际,但有JavaScript 中变量的实际用途是使用这种类型的封装。在下面的示例中,我们使用相同的概念来获取未定义数量的 HTML 元素的 ID。
此示例根据每个元素的 ID 声明可变变量(
elementIds
中的键),并将该元素的节点分配为每个变量的值。由于通常不鼓励在 JavaScript 中使用全局变量,因此为变量赋予唯一的作用域(在本例中,在elementIds
数组中声明它们)不仅简洁,而且更负责任。Unlike PHP, JavaScript doesn't offer access to the globals array (which contains references to all the variable names currently declared). As such, JavaScript does not offer native support for variable variables. You can, however, emulate this feature as long as you define all your variables as part of an array or an object. This will in turn create a globals array for you. For example, instead of declaring the variable
hello
in the global scope like this:Let's encapsulate it inside an object. We'll call that object
vv
(variable variables):Now we can refer to the variable by its index, and since array indexes can be provided using a variable, we are de facto making use of a variable variable:
The Answer To Your Question
Let's apply this to the code you supplied in the original question:
A Practical Use
While the previous code might appear ridiculously cumbersome and impractical, there are practical uses for variable variables in JavaScript using this type of encapsulation. In the example below we use the same concept to get the ID of an undefined number of HTML elements.
This example declares variable variables (keys in
elementIds
) based on the ID of each element, and will assign the node of said element as the value of each variable. And since using global variables in JavaScript is generally discouraged giving your variable variables a unique scope (in this instance, declaring them inside theelementIds
array) is not only neat, but also more responsible.当然可以,但不要这样做。变量必须是全局的。
Of course you can, but don't. The variables have to be global.
我用一个对象来做到这一点。无需使用 window:
只需确保 myVars 是全局的。
I do this with an object. No need to use window:
just make sure myVars is global.
您可以使用 JavaScript
eval(str)
函数。该函数将提供的字符串转换为 JavaScript 代码,然后执行它。
例如:
因此,要将其用作变量,您可以执行以下操作:
这将产生与以下完全相同的输出:(
示例取自 有关可变变量的 PHP 手册。)
You can use the JavaScript
eval(str)
function.This function converts the string provided into JavaScript code, and then executes it.
For example:
So to use it as a variable variable, you can do the following:
This will produce the exact same output as:
(Example is taken from the PHP manual on variable variables.)