es6 { [a]: b } 解构是什么意思?

What does the es6 { [a]: b } destructuring mean?

这里正在进行一些解构:

const { [a]: b } = this.props

但是,[a]: b 是做什么的:带冒号的括号是做什么的? 在我的例子中,a 作为具有字符串值的道具之一提供。

这个 ES6 解构语法与用于定义具有变量 属性 名称的对象的新 "Enhanced object literals" 非常相似,所以我认为先看看它是有用的:

ES6 之前,如果你想给一个对象赋值 属性 名称是可变的,你需要写

var obj = {};
obj[variable] = value

这是因为虽然点符号和对象文字符号都需要使用实际的 属性 名称,但 obj[prop] 符号允许您使用变量名。

ES6 引入了扩展对象字面量语法,which included the ability to write

var obj = { [variable]: value } 

解构中包含相同的语法,这就是您的问题所显示的。

基本的解构允许给变量赋值 属性 名字:

首先,分配给一个与对象 (docs) 中已有的 属性 同名的变量:

var person = {name: "Mary"};
var {name} = person;
/// name = "Mary"

其次,分配一个与对象中已有名称不同的变量 (docs):

var person = {name: "Mary"};
var {name: myName} = person;
/// myName = "Mary"

(旁注:如果您认识到,在第一个示例中,var {name} = ... 只是 var {name: name} = ... 的简写,您会发现这两个示例在逻辑上更匹配。)

但是如果您不知道 person 中的哪个 属性 怎么办?然后你可以使用上面相同的新计算-属性-name 对象语法 (docs):

var person = {name: "Mary"};
var propName = getPropUserWantToKnowAbout(); // they type in "name"
var {[propName]: value} = person;
/// value = "Mary"

一个例子

var props = {'dynamic': 2}
var dyn = 'dynamic'
const {[dyn]:a} = props
console.log(a);
// logs 2

查看此页面:https://gist.github.com/mikaelbr/9900818

简而言之,如果 dyn 是一个字符串,并且 props 有一个以该字符串作为名称的 属性,可由 props[dyn] 访问,那么 {[dyn]:a} = props 会将 props[dyn] 分配给 a

[a]computed property name

...allows you to put an expression in brackets [], that will be computed and used as the property name


{ [a]: b }destructuring assignment with assigning to new variable names 使用计算的 属性 名称

A property can be unpacked from an object and assigned to a variable with a different name than the object property


因此,您最终在当前范围内拥有一个变量 b,它保存 this.props[a]

的值

例子

this.props = {foo : 1, bar: 2};

let p1 = 'foo';
let p2 = 'bar';

let { [p1]: b } = this.props;

console.log(b); // 1

let { [p2]: c } = this.props;

console.log(c); // 2