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

后端 未结 7 1725
南旧
南旧 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:17

    To answer your question, this is the only way that I know of. It uses eval. But beware, eval is evil!

    var b = "foo";
    var a = eval('({ ' + b + ': ' + '"bar"' + ' })');
    

    This is an ugly solution. To play it safe you should not rely on this. Don't use it!

提交回复
热议问题