How to create a variable from the value of another variable
-
I need to create a variable from the value of another variable. As an example, this would be similar to how I would do this in VFP: nameOfNextVar = "port_no_1"; eval(nameOfNextVar) = 7493 Then I will be able to say: alert(port_no_1); And the alert would give me 7493... Is this possible in JavaScript??? TIA Dennis
-
Answer:
You can try something like this using JavaScript eval method. But using eval should be avoid if possible. var nameOfNextVar = "port_no_1"; eval(nameOfNextVar + " = " + 7493); alert(port_no_1); http://jsfiddle.net/ngTQf/ Other alternative is to define properties on the object or a current instance. You can also use window to define variables or properties. var nameOfNextVar = "port_no_1"; this[nameOfNextVar] = 7493; alert(this.port_no_1); window[nameOfNextVar] = 7493 alert(window.port_no_1); http://jsfiddle.net/ngTQf/2/
DKean at Stack Overflow Visit the source
Other answers
As a rule of thumb, you should try avoid eval when possible. However, if there is no other way, then you could do this: nameOfNextVar = "port_no_1"; eval("var " + nameOfNextVar + " = 7493"); alert(port_no_1); Hope that helps.
ralfe
Related Q & A:
- How to call a popup from a link inside another popup?Best solution by stackoverflow.com
- How to pass a variable from php to a modal?Best solution by Stack Overflow
- How to pass a variable from AlertDialog to an Activity?Best solution by Stack Overflow
- How to retrieve a variable name given its value?Best solution by Stack Overflow
- How to create a Database in FoxPro and how to retrieve and sort it out?Best solution by Yahoo! Answers
Just Added Q & A:
- How many active mobile subscribers are there in China?Best solution by Quora
- How to find the right vacation?Best solution by bookit.com
- How To Make Your Own Primer?Best solution by thekrazycouponlady.com
- How do you get the domain & range?Best solution by ChaCha
- How do you open pop up blockers?Best solution by Yahoo! Answers
For every problem there is a solution! Proved by Solucija.
-
Got an issue and looking for advice?
-
Ask Solucija to search every corner of the Web for help.
-
Get workable solutions and helpful tips in a moment.
Just ask Solucija about an issue you face and immediately get a list of ready solutions, answers and tips from other Internet users. We always provide the most suitable and complete answer to your question at the top, along with a few good alternatives below.