开发者

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

This question already has answers here: Closed 11 years ago.

Possible Duplicates:

Is there a way to access a javascript variable using a string that contains the name of the variable?开发者_如何学Python

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"


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];


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


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

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜