Javascript variable variables?

I know that in PHP it is possible to have "variables" variables. for example

$x = "variable"; $$x = "hello, world!"; echo $variable; // displays "hello, world!" 

Is it possible to refer to a variable by name as a string in JavaScript? How will this be done?

+87
javascript variables variable-variables
03 Mar. '11 at 10:40
source share
8 answers

There is no single solution for this (well, there is eval , but let's not seriously consider this). You can access some global variables dynamically through window , but this does not work for variables local to the function. Global variables that do not become a window property are variables defined with let and const , as well as class es.

There is almost always a better solution than using variable variables! Instead, you should look at the data structures and choose the right one for your problem.

If you have a fixed set of names like

 // BAD var foo = 42; var bar = 21; var key = 'foo'; console.log(eval(key)); 

save these names / values โ€‹โ€‹as properties of the object and use parenthesis to dynamically find them:

 // GOOD var obj = { foo: 42, bar: 21, }; var key = 'foo'; console.log(obj[key]); 

In ES2015 +, this is even easier to do for existing variables using a short notation of properties:

 // GOOD var foo = 42; var bar = 21; var obj = {foo, bar}; var key = 'foo'; console.log(obj[key]); 



If you have "sequentially" numbered variables such as

 // BAD var foo1 = 'foo'; var foo2 = 'bar'; var foo3 = 'baz'; var index = 1; console.log(eval('foo' + index)); 

then you should use an array instead and just use the index to access the corresponding value:

 // GOOD var foos = ['foo', 'bar', 'baz']; var index = 1; console.log(foos[index - 1]); 
+116
Mar 03 2018-11-11T00:
source share

If you desperately want to do this, you can try using eval ():

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

Or using a window object:

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

http://www.hiteshagrawal.com/javascript/dynamic-variables-in-javascript

+41
Mar 03 2018-11-11T00:
source share

To reference a variable in javascript with just a string, you can use

 window['your_variable_name'] 

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

+3
Nov 09 '14 at 0:50
source share

Of course you can, but don't. Variables must be global.

 var killingFunction = 'alert' var killMeNow = 'please' var please = 'You have been killed!' this[killingFunction](this[killMeNow]) 
+1
Oct 13 '12 at 18:07
source share
 var vars = {}; var var_name = "str"; vars[var_name] = "working"; console.log(vars["str"]); 
+1
Mar 10 '14 at 13:05
source share

You can use the JavaScript function eval(str) .

This function converts the string provided in JS code and executes it.

For example:

 eval("console.log('hello world')"); // Logs hello world 

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

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

This will give the same result as:

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

(An example from the PHP manual on variable variables .)

+1
Jul 12 '17 at 21:55
source share

Unlike PHP, JavaScript does not offer access to the globals array (which contains references to all declared variable names). Therefore, JavaScript does not offer native support for variable variables. You can, however, emulate this function as long as you define all of your variables as part of an array or object. This, in turn, will create an array of villains for you. For example, instead of declaring a hello variable in the global scope:

 var hello = 'hello world'; 

let it encapsulate it inside the object. We will call this object vv (variable variables):

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

Now we can refer to the variable at this index, and since array indices can be provided using the variable, we actually use the variable variable:

 console.log(vv[referToHello]); //Output: hello world 

The answer to your question

Apply this to the code provided in the original question:

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

Practical use

While the previous code may seem ridiculously cumbersome and impractical, there are practical uses of variable variables in JavaScript using this type of encapsulation. In the example below, we use the same concept to get the undefined identifier of the 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 identifier of each element and assigns the node of the specified element as the value of each variable. And since the use of global variables in JavaScript is usually not recommended, variable variables are a unique area (in this case, declaring them inside an elementIds array), not only neat, but also more responsible.

+1
Nov 20 '17 at 11:22
source share

We can use this.

 var objectName[key]{ 'someDataName':'thatData', 'someOtherDataName':'thisData' } 

If you want to get the value of a value, to use a loop

 for(key in objectName){ objectName[key].someDataName; objectName[key].someOtherDataName; } 
-2
Jun 01 '16 at 17:39
source share



All Articles