Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to display value of value of another variable?

Tags:

javascript

var foo = "bar" var bar  = "realvalue"; 

Is it possible to print the value of bar using foo ?

like image 304
Rakesh Juyal Avatar asked Dec 18 '12 08:12

Rakesh Juyal


People also ask

How do you set a variable to the value of another variable?

After a value is assigned to a variable using the assignment operator, you can assign the value of that variable to another variable using the assignment operator. var myVar; myVar = 5; var myNum; myNum = myVar; The above declares a myVar variable with no value, then assigns it the value 5 .

How do you show the value of a variable in Matlab?

Command Window — To view the value of a variable in the Command Window, type the variable name. For the example, to see the value of a variable n , type n and press Enter. The Command Window displays the variable name and its value.

How do you pass value from one variable to another in JavaScript?

Here is some code: window. onload = function show(){ var x = 3; } function trig(){ alert(x); } trig();

How do you assign a value to another variable in Python?

Python will joyfully accept a variable by that name, but it requires that any variable being used must already be assigned. The act of assignment to a variable allocates the name and space for the variable to contain a value. We saw that we can assign a variable a numeric value as well as a string (text) value.


2 Answers

Approach 1: global variable

var foo = "bar"; var bar  = "realvalue"; alert(window[foo]); 

OR

Approach 2: namespace
Divide your js to namespaces

var namespace = {  foo : "bar",  bar : "realvalue" }; alert(namespace[namespace.foo]); 
like image 93
Akhil Sekharan Avatar answered Oct 13 '22 12:10

Akhil Sekharan


Yeah you can do something like this with eval

var foo = "bar"; var bar  = "realvalue"; alert(eval(foo)); 

EDIT: Seems a lot of people are against using the eval() function. My advice before using it is read this question: Why is using the JavaScript eval function a bad idea?

Then once you understand the risks you can decide for yourself if you wish to use it.

like image 35
cowls Avatar answered Oct 13 '22 12:10

cowls