Is it possible to define a dynamically named property using object literal in JavaScript?

后端 未结 7 1655
南旧
南旧 2021-01-17 16:05

Consider the following

var a = {foo: \"bar\"};

Equivalent to

var a = {};
a.foo = \"bar\";

Equivalent to

7条回答
  •  悲哀的现实
    2021-01-17 16:26

    No.

    There is no way to do it using object literal notation.


    UPDATE: According to the ECMAScript standard 6.0 you are now able to do the following:

    var b = 'foo';
    var a = { [b]: 'bar' };
    
    console.log( a.foo );  // "bar"
    

    However, this solution won't work in old browsers, which do not support ES6.

提交回复
热议问题