ES6双重解构 [英] ES6 double destructure

查看:80
本文介绍了ES6双重解构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我了解这可能是一个非常基本的问题,但是我不精通ES6,并且遇到了以下语法:

I understand this probably is a pretty basic question, but I'm not proficient with ES6 and I've encountered this syntax:

const { rootStore: { routerStore } } = this.props;

我了解类似的意思

const { rootStore } = this.props;

(从 this.props 中的属性 rootStore 创建一个const rootStore ).

(Creating a const rootStore from the property rootStore in this.props).

但是上面的双重解构(我认为是解构)是什么意思?

But what does the above double deconstruction (I assume it's deconstruction) mean?

推荐答案

这称为嵌套解构,它在许多情况下非常有用

This is called nested destructuring and its very useful in many situations

让我们一点一点地了解它,

let's understand it bit by bit ,

看这个例子

const person = {
    friend: {
        name: 'john',
        age: 20,
    },
};

const { friend } = person;

console.log(friend);

在这里,我们使用解构来获得prop朋友的值,并且值本身是一个对象,我们也可以对其进行解构,

here we get the value of the prop friend using destructuring and the value itself is an object and we can use destructring with it as well ,

来自上一个示例

const person = {
    friend: {
        name: 'john',
        age: 20,
    },
};

const { friend } = person;

console.log(friend);

const {age} = friend ;

console.log(age) ; 

现在我们也可以通过分解获得年龄道具,这非常方便,但是如果我只需要年龄道具而又不需要朋友道具,我可以一步一步完成所有上述示例吗?是的 !!这就是ES6的出色之处,

now we get the age prop using destructuring as well and that's pretty and super handy , but what if I just need the age prop and I don't need the friend prop , can I do all the above example in one step , Yes !! and that's the awesomeness of ES6 ,

const person = {
    friend: {
        name: 'john',
        age: 20,
    },
};

const { friend :{age} } = person;

console.log(age); 

您可以看到我们一步一步就能得到 age 的值,在嵌套对象的许多情况下这很有用,在上面的代码中,如果您尝试记录好友的值,会得到 ReferenceError:未定义朋友

as you can see we get the value of age in one step and that's useful in many situations when you have nested objects , in the code above if you try to log the value of friend you'll get ReferenceError: friend is not defined ,

你知道吗?您可以根据需要进行深层嵌套的解构,看看这个有趣的复杂例子.

Did you know ? you can make deep nested destructuring as you want , look at this complex example which is just for fun .

const person = {
    friend: {
        name: 'john',
        other: {
            friend: {
                name: {
                    fullName: {
                        firstName: 'demo',
                    },
                },
            },
        },
    },
};

const {
    friend: {
        other: {
            friend: {
                name: {
                    fullName: { firstName },
                },
            },
        },
    },
} = person;

console.log(firstName); // demo

漂亮!

如果您想了解有关解构的所有知识,请查看此资源

if you want to know everything about destructuring look at this resources

解构分配MDN

ECMAScript 6中的解构和参数处理

这篇关于ES6双重解构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆