是否有与 PHP 的“变量”等效的 JavaScript?

发布于 2024-10-20 05:27:46 字数 346 浏览 7 评论 0原文

我知道 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(9

潦草背影 2024-10-27 05:27:46

tl;dr:不要使用< code>eval!

对于这个问题没有单一的解决方案。可以通过窗口动态访问一些全局变量,但这不适用于函数的本地变量。 成为window属性的全局变量是用letconst定义的变量,以及类。

几乎总是有比使用可变变量更好的解决方案! 相反,您应该查看数据结构 并选择适合您问题的选项。

如果您有一组固定的名称,例如

// BAD - DON'T DO THIS!!!
var foo = 42;
var bar = 21;

var key = 'foo';
console.log(eval(key));

将这些名称/值存储为对象的属性,并使用括号表示法动态查找它们:

// GOOD
var obj = {
  foo: 42,
  bar: 21,
};

var key = 'foo';
console.log(obj[key]);

ES2015+ 中,使用简洁的属性表示法对现有变量执行此操作甚至更容易:

// GOOD
var foo = 42;
var bar = 21;
var obj = {foo, bar};

var key = 'foo';
console.log(obj[key]);


如果您有“连续”编号的变量,例如

// BAD - DON'T DO THIS!!!
var foo1 = 'foo';
var foo2 = 'bar';
var foo3 = 'baz';

var index = 1;
console.log(eval('foo' + index));

那么你应该使用数组来代替,并简单地使用索引来访问相应的值:

// GOOD
var foos = ['foo', 'bar', 'baz'];
var index = 1;
console.log(foos[index - 1]);

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));

store those names/values as properties of an object and use bracket notation to look them up dynamically:

// GOOD
var obj = {
  foo: 42,
  bar: 21,
};

var key = 'foo';
console.log(obj[key]);

In ES2015+ it's even easier to do this for existing variables using concise property notation:

// GOOD
var foo = 42;
var bar = 21;
var obj = {foo, bar};

var key = 'foo';
console.log(obj[key]);


If you have "consecutively" numbered variables, such as

// BAD - DON'T DO THIS!!!
var foo1 = 'foo';
var foo2 = 'bar';
var foo3 = 'baz';

var index = 1;
console.log(eval('foo' + index));

then you should be using an array instead and simply use the index to access the corresponding value:

// GOOD
var foos = ['foo', 'bar', 'baz'];
var index = 1;
console.log(foos[index - 1]);

铜锣湾横着走 2024-10-27 05:27:46

如果您迫切希望这样做,您可以尝试使用 eval():

var data = "testVariable";
eval("var temp_" + data + "=123;");
alert(temp_testVariable);

或使用 window 对象:

var data = "testVariable";
window["temp_" + data] = 123;
alert(window["temp_" + data]);

If you are desperate to do this you can either try using eval():

var data = "testVariable";
eval("var temp_" + data + "=123;");
alert(temp_testVariable);

Or using the window object:

var data = "testVariable";
window["temp_" + data] = 123;
alert(window["temp_" + data]);
我还不会笑 2024-10-27 05:27:46

要仅使用字符串引用 JavaScript 中的变量,您可以使用

window['your_variable_name']

You can set and reference Variables, and objects in Variables so。

To reference a variable in JavaScript with only a string, you can use

window['your_variable_name']

You can set and reference variables, and objects in variables too.

℉服软 2024-10-27 05:27:46

您可以使用全局window对象,或this

window

var data = "anyVariableName";
window["temp_" + data] = 123;
alert(window["temp_" + data]); //123

或使用点:

var data = "anyVariableName";
window.data = 123;
alert(window.data); //123

This:

ar data = "anyVariableName";
this["temp_" + data] = 123;
alert(this["temp_" + data]); //123

或使用点

var data = "anyVariableName";
this.data = 123;
alert(this.data); //123

一个现实生活中的例子:

var tasksTableNameRandom = 'tasksTable_' + Math.random().toString(36).substr(2, 5);
console.log('Tasks Table Object name: ' + tasksTableNameRandom);
this.tasksTableNameRandom = $('#tasks-data-table').DataTable({
    ...
});

You can use the global window object, or this:

window:

var data = "anyVariableName";
window["temp_" + data] = 123;
alert(window["temp_" + data]); //123

Or using dot:

var data = "anyVariableName";
window.data = 123;
alert(window.data); //123

This:

ar data = "anyVariableName";
this["temp_" + data] = 123;
alert(this["temp_" + data]); //123

or using dot

var data = "anyVariableName";
this.data = 123;
alert(this.data); //123

A real-life example:

var tasksTableNameRandom = 'tasksTable_' + Math.random().toString(36).substr(2, 5);
console.log('Tasks Table Object name: ' + tasksTableNameRandom);
this.tasksTableNameRandom = $('#tasks-data-table').DataTable({
    ...
});

与 PHP 不同,JavaScript 不提供对全局数组(其中包含对当前声明的所有变量名称的引用)的访问。因此,JavaScript 不提供对变量的本机支持。但是,只要将所有变量定义为数组或对象的一部分,您就可以模拟此功能。这将为您创建一个全局数组。例如,不要像这样在全局作用域中声明变量 hello

var hello = 'Hello, World!';

让我们将其封装在一个对象内。我们将调用该对象 vv (变量变量):

var vv = {
    'hello': 'Hello, World! ',
    //Other variable variables come here.
},
referToHello = 'hello';

现在我们可以通过变量的索引引用该变量,并且由于可以使用变量提供数组索引,因此我们实际上正在使用变量变量:

console.log(vv[referToHello]); //Output: Hello, World!

问题的答案

让我们将其应用到您在原始问题中提供的代码:

    var vv = {
        'x': 'variable',
        'variable': 'Hello, World!'
    };
    console.log(vv[vv['x']]); // Displays "Hello, World!"

实际用途

虽然前面的代码可能显得非常繁琐和不切实际,但有JavaScript 中变量的实际用途是使用这种类型的封装。在下面的示例中,我们使用相同的概念来获取未定义数量的 HTML 元素的 ID。

var elementIds = [],
        elements = ['message','fillOrStroke','sizePicker','colorPicker']; //The items in this array could be defined automatically via an input, database query, event, etc.
        elements.forEach( (element) => {
            elementIds[element] = document.getElementById(element);
        });

此示例根据每个元素的 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:

var hello = 'Hello, World!';

Let's encapsulate it inside an object. We'll call that object vv (variable variables):

var vv = {
    'hello': 'Hello, World! ',
    //Other variable variables come here.
},
referToHello = 'hello';

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:

console.log(vv[referToHello]); //Output: Hello, World!

The Answer To Your Question

Let's apply this to the code you supplied in the original question:

    var vv = {
        'x': 'variable',
        'variable': 'Hello, World!'
    };
    console.log(vv[vv['x']]); // Displays "Hello, World!"

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.

var elementIds = [],
        elements = ['message','fillOrStroke','sizePicker','colorPicker']; //The items in this array could be defined automatically via an input, database query, event, etc.
        elements.forEach( (element) => {
            elementIds[element] = document.getElementById(element);
        });

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 the elementIds array) is not only neat, but also more responsible.

无声情话 2024-10-27 05:27:46
var vars = {};
var var_name = "str";
vars[var_name] = "working";
console.log(vars["str"]);
var vars = {};
var var_name = "str";
vars[var_name] = "working";
console.log(vars["str"]);
寂寞笑我太脆弱 2024-10-27 05:27:46

当然可以,但不要这样做。变量必须是全局的。

var killingFunction = 'alert'
var killMeNow = 'please'
var please = 'You have been killed!'
this[killingFunction](this[killMeNow])

Of course you can, but don't. The variables have to be global.

var killingFunction = 'alert'
var killMeNow = 'please'
var please = 'You have been killed!'
this[killingFunction](this[killMeNow])

假扮的天使 2024-10-27 05:27:46

我用一个对象来做到这一点。无需使用 window:

var myVars = {};

let foo = "hello";
myVars[foo] = 100;
let bar = myVars[foo];

只需确保 myVars 是全局的。

I do this with an object. No need to use window:

var myVars = {};

let foo = "hello";
myVars[foo] = 100;
let bar = myVars[foo];

just make sure myVars is global.

狂之美人 2024-10-27 05:27:46

您可以使用 JavaScript eval(str) 函数。

该函数将提供的字符串转换为 JavaScript 代码,然后执行它。

例如:

eval("console.log('Hello, World!')"); // Logs hello world

因此,要将其用作变量,您可以执行以下操作:

var a = "Hello,";
var hello = "World!";
console.log(a + " " + eval(a)); // Logs hello world

这将产生与以下完全相同的输出:(

console.log(a + " " + hello); // Logs hello world

示例取自 有关可变变量的 PHP 手册。)

You can use the JavaScript eval(str) function.

This function converts the string provided into JavaScript code, and then executes it.

For example:

eval("console.log('Hello, World!')"); // Logs hello world

So to use it as a variable variable, you can do the following:

var a = "Hello,";
var hello = "World!";
console.log(a + " " + eval(a)); // Logs hello world

This will produce the exact same output as:

console.log(a + " " + hello); // Logs hello world

(Example is taken from the PHP manual on variable variables.)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文