Javascript 如何在Javascript中使用字符串作为变量名?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6160146/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 20:29:39  来源:igfitidea点击:

How to use a string as a variable name in Javascript?

javascript

提问by Sussagittikasusa

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

可能的重复:
有没有办法使用包含变量名称的字符串访问 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 ) 

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

我希望变量 new 被分配变量的值 - chat_1 是“一”

回答by Quentin

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

回答by bgcode

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

资料来源:http: //www.i-marco.nl/weblog/archive/2007/06/14/variable_variables_in_javascri

回答by Russell Davis

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

您可以使用全局window对象,假设这些未在函数中定义:

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