ES6(五)解构:更方便的数据访问2

2020-05-17  本文已影响0人  蒋小花_4b6c

1.混合解构

2.参数解构

混合解构

对象与数组解构能被用在一起,以创建更复杂的解构表达式。

let node = {

    type: "Identifier",

    name: "foo",

    loc: {

        start: {

            line: 1,

            column: 1

        },

        end: {

            line: 1,

            column: 4

        }

    },

    range: [0, 3]

};

let {

    loc: {

        start

    },

    range: [

        startIndex

    ]

} = node;

console.log(start.line);

console.log(start.column);

console.log(startIndex);

要记住解构模式中的 loc: 与 range: 只是对应于 node 对象中属性的位 置。

混合使用对象与数组解构, node 的任何部分都能提取出来。

对于从 JOSN 配置结构中 抽取数据来说,这种方法尤其有用,因为它不需要探索整个结构。

参数解构

在传递函数参数时,

当 JS 的函数接收大量可选参数时,一 个常用模式是创建一个 options  对象,其中包含了附加的参数

// options 上的属性表示附加参数

function setCookie(name, value, options) {

    options = options || {};

    let secure = options.secure,

        path = options.path,

        domain = options.domain,

        expires = options.expires;

    // 设置 cookie 的代码

}

// 第三个参数映射到 options

setCookie("type", "js", {

        secure: true,

        expires: 60000

    }

);

function setCookie(name, value, { secure, path, domain, expires }) {

    // 设置 cookie 的代码

}   

setCookie("type", "js", { secure: true, expires: 60000}

);

如果这样调用则会报错,没有解构参数

setCookie("type", "js");

为了避免这种报错,可以这样:

function setCookie(name, value, { secure, path, domain, expires } = {}) {

}

解构的对象给一个默认值{}。

同样如果有需要,可以给每个结构的参数都赋默认值:

function setCookie(

    name,

    value,

    {

        secure = false, path = "/",

        domain = "example.com",

        expires = new Date(Date.now() + 360000000)

    } = {}

) {

    // ...

}

上一篇 下一篇

猜你喜欢

热点阅读