How to create variable from value in variable?

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

Was this solution helpful to you?

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:

Just Added Q & A:

Find solution

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.