方括号Javascript对象键


109

谁能解释下面的JavaScript分配键方法为何/如何工作?

a = "b"
c = {[a]: "d"}

返回:

Object {b: "d"}

Answers:



27

实际上,在创建JavaScript 对象时,的使用[]提供了一种使用变量的实际值作为/属性的绝妙方法。

我对上述答案非常满意,对此我非常感激,因为它使我可以举一个小例子。

我已经在Node REPL(Node shell)上逐行执行了代码。

> var key = "fullName";     // Assignment
undefined
>
> var obj = {key: "Rishikesh Agrawani"}    // Here key's value will not be used
undefined
> obj     // Inappropriate, which we don't want
{ key: 'Rishikesh Agrawani' }
>
> // Let's fix
undefined
> var obj2 = {[key]: "Rishikesh Agrawani"}
undefined
> obj2
{ fullName: 'Rishikesh Agrawani' }
>

6
const animalSounds = {cat: 'meow', dog: 'bark'};

const animal = 'lion';

const sound = 'roar';

{...animalSounds, [animal]: sound};

结果将是

{cat: 'meow', dog: 'bark', lion: 'roar'};

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.