How to use string as variable name in javascript?

Possible duplicates:
Is there a way to access the javascript variable using a string containing the variable name?
JavaScript: get a local variable dynamically by name string

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 new variable to be assigned the value of the variable - chat_1, which is "one"

+3
source share
3 answers

Stop. Reorganize your code. If you want to select variables with a variable, there must 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];
+26
source

This is not a good practice, but you can do it like this:

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

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

+5

window, :

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

All Articles