如何在Javascript中使用字符串作为变量名?
问题描述:
可能重复:
有没有办法使用包含变量名称的字符串来访问javascript变量?
JavaScript:按名称动态获取局部变量字符串
一个简单的代码来说明我的问题 -
A simple code to illustrate my problem -
var chat_1 = "one";
var chat_2 = "two";
var id = "1";
var new = ?? variabalize( 'chat_' + id )
我希望变量new赋值变量 - chat_1是一个
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];