简体   繁体   中英

Inline object literal with a variable property

Why does Javascript syntax not support inline object literals with a variable property? 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?

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.

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" . This only works in the implementations that support this syntax of course.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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