Javascript 在Javascript中连接动态变量名称

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12149233/
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 07:13:52  来源:igfitidea点击:

Concatenate a dynamic variable name in Javascript

javascriptvariables

提问by jason328

In PHP you can concatenate a variable name like this

在 PHP 中,您可以像这样连接变量名

$a = 1

${'fruit_' . $a} = 'apple';

The result will lead to the creation of variable $fruit_a

结果将导致创建变量 $fruit_a

How would I do this in javascript?

我将如何在 javascript 中做到这一点?

回答by Jo?o Silva

Not sure exactly what you are trying to accomplish, but with JavaScript, you could use the following:

不确定您要完成什么,但是使用 JavaScript,您可以使用以下内容:

> var a = 1;
> var b = {};
> b['fruit_' + a] = 'apple';
> b.fruit_1
"apple"
> b['fruit_1']
"apple"

回答by Ethan Brown

var a = 1;
this['fruit_' + a] = 'apple';

console.log( fruit_1 );