方括号 Javascript 对象键

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32515598/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 10:32:37  来源:igfitidea点击:

Square Brackets Javascript Object Key

javascript

提问by lcharbon

Can anyone explain how the why/how the below method of assigning keys in javascript works?

任何人都可以解释为什么/如何在javascript中分配键的以下方法是如何工作的?

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

return:

返回:

Object {b: "d"}

回答by Sean Vieira

It's the new ES2015 (the EcmaScript spec formally known as ES6) computed property name syntax. It's a shorthand for the someObject[someKey]assignment that you know from ES3/5:

它是新的 ES2015(正式称为 ES6 的 EcmaScript 规范)计算属性名称语法。这someObject[someKey]是您在 ES3/5 中知道的作业的简写:

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

is syntactic sugar for:

是语法糖:

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

回答by hygull

Really the use of []gives an excellent way to use actual value of variable as key/propertywhile creating JavaScript objects.

确实,使用[]提供了一种极好的方法,可以在创建 JavaScript对象时使用变量的实际值作为关键/属性

I'm pretty much statisfied with the above answer and I appreciate it as it allowed me to write this with a little example.

I've executed the code line by line on Node REPL(Node shell).

我对上面的答案非常满意,我很感激,因为它让我可以用一个小例子来写这个。

我已经在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' }
>

回答by monireh d

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

const animal = 'lion';

const sound = 'roar';

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

The result will be

结果将是

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

回答by Eldiyar Talantbek

Also, only condition to use []notation for accessing or assigning stuff in objects when we don't yet know what it's going to be until evaluation or runtime.

此外,只有[]在评估或运行时我们还不知道它将是什么时,才可以使用符号来访问或分配对象中的内容。