3

I have a problem that I hope to use one variable's contents as another variables name in javascript. In this case, I do not know what is the contents in that variable, I only know it is a text type and I hope the variable I need to declare will use that text as its name.

Anyone could kindly give me some suggestion of how to do that?

Thank you!

1

2 Answers 2

3

You are able to use a variable's value as another variable's name as long as the latter variable can be accessed via bracket notation, e.g.

var firstVariable = 'secondVariable';

window[firstVariable] = 'secondValue';
// you now have a global variable 
// named "secondVariable" with the value "secondValue"

Note I would not recommend cluttering the global namespace like this; it was just for demonstration.

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

Comments

3

You can't really, variable names (identifiers) are static (as long as you don't use eval) in a scope.

However, you can easily use objects for that. Accessing properties of them with a variable name is easy, use the bracket notation:

var obj = { someprop:"someval", otherprop:… },
    name = "someprop";
obj[name]; // "someval"

If you need a global variable, you can do that by accessing it as a property of the global object (in browsers: window):

variable = "someval";
var name = "variable";
window[name]; // "someval"

Comments

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.