JavaScript 对象声明语法 - 变量名作为属性

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

JavaScript object declaration syntax - variable names as properties

javascriptobjectsyntax

提问by tommcdo

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:

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

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"

or

或者

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'
};

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

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

Thanks.

谢谢。

采纳答案by dwhieb

ES6 now allows for this:

ES6 现在允许这样做:

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

回答by geekman

No, this will not work, that is why, if you are dynamically setting property names, array like notation is suggested and used.

不,这行不通,这就是为什么,如果您动态设置属性名称,建议并使用类似符号的数组。

var k='propertyname';
object[k]="value";

this works while using the dot notation to set index or property name from vatiable is not possible.

这在使用点符号从 vatiable 设置索引或属性名称是不可能的时有效。

回答by Zack Morris

For people who need a drop-in replacement for dot syntax where the keys are objects instead of strings (say for nesting inside a parent Object), here are some workarounds:

对于需要直接替换点语法的人,其中键是对象而不是字符串(比如嵌套在父对象中),这里有一些解决方法:

var developers = {
    person: {
        'name': 'John',
        'age': 23
    },
    anarchist: (function(){ var a = {};
        a['name'] = 'John';
        a['age'] = 23;
        a[false] = false;
        a[1] = 1;
        a[window] = window;
    return a; })(),
    conformist: _.object([
        ['name', 'John'],
        ['age', 23],
        [false, false],
        [1, 1],
        [window, window]
    ])
};

// console.log(developers); // <- to see var dump in Firebug

The anarchist element uses a self-executing-functionthat gets garbage collected after the call, and the conformist element uses the _.object()function if you can include underscore.js in your site.

anarchist 元素使用自执行函数在调用后收集垃圾,如果您可以在站点中包含 underscore.js,conformist 元素使用_.object()函数。

I wish that the built-in Object() and Array() functions allowed for passing in keys and values the way underscore.js does it :-)

我希望内置的 Object() 和 Array() 函数允许以 underscore.js 的方式传递键和值:-)

回答by sra

You can not do this with objects, but if you consider using a constructor function instead, it could look something like this:

你不能使用对象做到这一点,但如果你考虑使用一个构造函数,而不是,它可能是这个样子:

var prop = "birthday";
var Person = function() {
    this.name = "Bob";
    this[prop] = "January 12";
};
var bob = new Person();

Of course you still have the array notation here, but maybe you like this aproach anyway :)

当然,这里仍然有数组表示法,但也许您仍然喜欢这种方法:)