0

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

1

2 Answers 2

5

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.

Sign up to request clarification or add additional context in comments.

3 Comments

you rock... It is similar to how we do it in VFP, but this eval simply evaluates the text. In VFP you can say "print eval(nameOfNextVar)" and get back 7493. Can that be done in JavaScript??
you could have eval("print " + nameOfNextVar );.
Actually, I tried it and id does the eval like VFP. Many thanks, @ralfe
2

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/

2 Comments

Yes that works @ShankarSangoli Thank you for the quick response. And thanks for the fiddle!
And thank you for the alternatives. I think I like this option better: "window[nameOfNextVar] = ..." Good suggestion @ShankarSangoli

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.