变量作为JavaScript对象文字中的属性名称? [英] Variable as the property name in a JavaScript object literal?
问题描述
可能重复:
如何使用变量作为名称向Javascript对象添加属性?
在JavaScript文字中使用变量作为属性名称?
是否可以在JavaScript中添加变量作为对象的属性名称,像这样:
Is it possible to add a variable as the property name of an object in JavaScript, like this:
var myVar = "name";
var myObject = {
{myVar}: "value"
};
推荐答案
您可以使用 [ ]
使用表达式作为属性名称的语法(与 .prop
和相比较prop:value
语法,它们总是被视为字符串):
You can use the []
syntax to use an expression as the property name (compared to the .prop
and prop: value
syntaxes where they are always treated as strings):
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.
使用ES6,现在可以使用 ComputedPropertyName ,以下列语法的形式显示:
With ES6, this is now possible using a ComputedPropertyName, which manifests in the form of the following syntax:
var myVar = "name";
var myObject = {
[myVar]: "value"
};
这篇关于变量作为JavaScript对象文字中的属性名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!