变量作为 JavaScript 对象文字中的属性名称?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11043026/
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
Variable as the property name in a JavaScript object literal?
提问by jsgroove
Possible Duplicate:
How do I add a property to a Javascript Object using a variable as the name?
Use variable for property name in JavaScript literal?
可能的重复:
如何使用变量作为名称向 Javascript 对象添加属性?
在 JavaScript 文字中使用变量作为属性名称?
Is it possible to add a variable as the property name of an object in JavaScript, like this:
是否可以在 JavaScript 中添加变量作为对象的属性名称,如下所示:
var myVar = "name";
var myObject = {
{myVar}: "value"
};
回答by ThiefMaster
You can use the []
syntax to use an expressionas the property name (compared to the .prop
and prop: value
syntaxes where they are always treated as strings):
您可以使用以下[]
语法将表达式用作属性名称(与始终将它们视为字符串的.prop
和prop: value
语法相比):
var myObject = {};
var myVar = "name";
myObject[myVar] = "value";
There is no way to use that inside an object literal, though. You have to create the object first and then assign each property separately.
但是,无法在对象文字中使用它。您必须先创建对象,然后分别分配每个属性。
Edit
编辑
With ES6, this is now possible using a ComputedPropertyName, which manifests in the form of the following syntax:
在 ES6 中,现在可以使用ComputedPropertyName,它以以下语法的形式出现:
var myVar = "name";
var myObject = {
[myVar]: "value"
};
回答by Blender
Like this?
像这样?
var myVar = "name";
var myObject = {};
myObject[myVar] = "value";
回答by Niet the Dark Absol
Yes, but not directly.
是的,但不是直接的。
var myVar = "name";
var object = {};
object[myVar] = "value";