Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use a string as a variable name in Javascript? [duplicate]

Tags:

javascript

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"

like image 690
Sussagittikasusa Avatar asked Nov 27 '22 04:11

Sussagittikasusa


1 Answers

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];
like image 75
Quentin Avatar answered Dec 09 '22 17:12

Quentin