4

Possible Duplicates:
Is there a way to access a javascript variable using a string that contains the name of the variable?
JavaScript: Get local variable dynamicly by name string

A simple code to illustrate my problem -

var chat_1 = "one";

var chat_2 = "two";

var id = "1";

var new = ?? variabalize( 'chat_' + id ) 

I want the variable new to be assigned the value of variable - chat_1 which is "one"

4

3 Answers 3

27

Stop. Reorganise your code. If you want to select variables with a variable, then there has to be a logical grouping for them. Make it explicit.

var chat = {
    "1": "one",
    "2": "two"
};
var id = 1;
var new_is_a_keyword_and_cant_be_an_identifier = chat[id];
Sign up to request clarification or add additional context in comments.

1 Comment

Hey thank you for replying, this looks live a very nice way of doing what I wanted. Also how do I add more "keys"/variables to this main chat variable?
6

This is not a good practice, but you can do it as follows:

var i=1;
//window['name' + i] will now access the variable

Source: http://www.i-marco.nl/weblog/archive/2007/06/14/variable_variables_in_javascri

1 Comment

+1 But I would emphasis NOT GOOD PRACTICE. Most of the time code like this is a result of coming from certain "other" languages... It must be pointed out this only works on "global variables" and will not work for variables defined within a function.
2

You can use the global window object, assuming these are not defined inside a function:

var new = window['chat_' + id];

3 Comments

They are locally scoped variables. That won't work inside a function.
@Quentin They may be locally scoped (and the second statement holds). However, the question is vague on this and it will work for "global variables".
+1 for answering the question. Providing warnings and context is fine, but I hate it when people give lectures instead of answering the question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.