本文介绍了JavaScript 对象声明语法 - 变量名作为属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

JavaScript 为您提供了多种声明对象的方法.当您手头有大部分可用数据时,最方便的(在我看来)如下:

JavaScript gives you a lot of ways to declare objects. When you have most of the data available at hand, the most convenient (in my opinion) is as follows:

var person = {
    name: 'John',
    age: 23
}; // "object literal syntax"

这个语法的一个奇怪之处在于它与此相同:

A curious thing about this syntax is that it is identical to this:

var person = {
    'name': 'John',
    'age': 23
}; // "object literal syntax"

也就是说,您可以对属性名称使用引号或省略它们.

That is, you can use quotes or omit them for the property names.

将其与设置单个属性的工作方式进行比较时,您有两种选择:

When comparing that to the way setting a single property works, you have two options:

person.birthday = "January 12"; // "dot syntax"

person['birthday'] = "January 12"; // "array syntax"

点语法"仅在正确的操作数是实际属性名称时才有效.如果要为属性名称使用变量,则必须使用数组语法",即:

The "dot syntax" only works when the right operand is the actual property name. If you want to use a variable for the property name, you have to use "array syntax", i.e.:

var prop = "birthday";
person[prop] = "January 12";

现在,是否可以在对象文字语法"中为属性名称使用变量?由于引用属性名称无关紧要,因此似乎没有明显的方法可以在那里使用变量.我正在寻找这样的东西:

Now, is it possible to use a variable for the property name in the "object literal syntax"? Since it doesn't matter if you quote the property names, there doesn't seem to be an obvious way to use a variable there. I'm looking for something like this:

var prop = "birthday";
var person = {
    name: 'John',
    age: 23,
    (prop): 'January 12'
};

这里我使用 (prop) 作为虚构的语法,用于表示这是一个变量而不是文字字符串.

Here I'm using (prop) as the imaginary syntax used to express that this is a variable and not a literal string.

谢谢.

推荐答案

ES6 现在允许这样做:

ES6 now allows for this:

var obj = {
  [prop]: 'value'
};

这篇关于JavaScript 对象声明语法 - 变量名作为属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-22 16:33