简体   繁体   English

具有可变属性的内联对象文字

[英]Inline object literal with a variable property

Why does Javascript syntax not support inline object literals with a variable property? 为什么Javascript语法不支持带有变量属性的内联对象文字? For example: 例如:

const f = function (arg) {
  console.log(arg);
}

f({}['some key'] = 1) // 1
f({ 'some key' : 1})  // [object Object] { some key: 1 }

Is there another alternative other than the two steps? 除了这两个步骤之外,还有其他选择吗?

var o = {}
o['some key'] = 1
f(o)

Thanks! 谢谢!

Why does Javascript syntax not support inline object literals with a variable property? 为什么Javascript语法不支持带有变量属性的内联对象文字?

You seem to be asking about variable properties, yet your examples do not use variables. 您似乎在询问变量属性,但是您的示例未使用变量。 Specifically, this example will work just fine. 具体来说,此示例可以正常工作。

f({ 'some key' : 1})

However, if you actually did want to use a variable without first creating the object, ECMAScript 6 now allows this. 但是,如果您确实想在不首先创建对象的情况下使用变量,则ECMAScript 6现在允许这样做。

So if this is your variable: 因此,如果这是您的变量:

var my_variable = 'some key';

You can now use square brackets around the property name in the object literal, and it will use the value of the expression you provide: 现在,您可以在对象文字中的属性名称周围使用方括号,它将使用您提供的表达式的值:

var o = {[my_variable]: 1};

The o object will have a property named "some key" . o对象将具有一个名为"some key"的属性。 This only works in the implementations that support this syntax of course. 当然,这仅在支持此语法的实现中起作用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM