@Dale-Lin
2018-06-24T13:36:04.000000Z
字数 2162
阅读 1020
深入理解ES6
let node = {type: "Identifier",name: "foo"};let {type, name} = node;
上例是为属性同名变量的解构。
let node = {type: "Identifier",name: "foo"},type = "literal",name = "5";//赋值由于没有 let 操作符,需要用括号,否则报错({name, type} = node);
如果解构的右侧为 undefined 或 null,会抛出错误(无法读取属性)。
let node = {type: "Identifier",name: "foo"}let {type, name, value = true} = node;
如果对象解构表达式左边有右侧对象不存在的属性,则会赋值为 undefined。
在解构表达式左边的变量后使用 = ,表示为变量设置默认值。
let node = {type: "Identifier",name: "foo"};let {name: localName, type: localType} = node;
为非同名变量 localName 和 localType 赋值。
在对象解构模式中,使用 {} 意味着向该下层对象解构:
let node = {type: "Identifier",name: "foo",loc: {start: {line: 1,column: 1},end: {line: 1,column: 4}}};let {loc: { start: localStart }} = node;console.log(localStart.line); //1console.log(localStart.column); //1
数组解构使用数组字面量,并将变量对应数组位置赋值:
let colors = ["red", "green", "blue];let [firstColor, secondColor] = colors;console.log(firstColor); //"red"console.log(secondColor); //"green"
当通过 var 、let 或 const 声明数组解构/对象解构的绑定时,必须提供一个初始化程序
使用数组字面量,不需要括号:
let colors = ["red", "green", "blue"],firstColor = "black",secondColor = "purple";[firstColor, secondColor] = colors;
数组结构赋值用于两个变量值的交换时,不需要额外的变量:
let a = 1,b = 2;[a, b] = [b, a];
let colors = ["red"];let [firstColor, secondColor = "green"] = colors;
依旧在解构表达式左边使用 = 设置默认值。
在解构表达式内使用 [] 表示向下层数组解构:
let colors = ["red", ["green", "lightgreen"], "blue"];let [firstColor, [secondColor]] = colors;
或使用不定参数为变量赋值一个内嵌的数组:
let colors = ["red", "green", "blue"];let [firstColor, ...restColors] = colors;
不定参数只能放在末尾!
在 ES5 中,由于数组是实例对象,深复制要使用 concat() 方法。
在 ES6 中,使用( 数组解构 + 不定参数 )可以深复制数组对象:
let colors = [a, b, c];let [...clonedColors] = colors;
解构可以用在函数参数的传递过程中。
当函数需要接受大量可选参数时,通常会创建一个可选对象,将额外的参数定义为该对象的属性:
function setCookie(name, value, {secure, path, domain, expires}) {//code}setCookie("type", "js", {secure: false,expires: 60000});
在声明函数的时候,显式地设置解构等式左边的部分作为可选参数,能让解构更易读。
此时 setCookie() 函数必须传入第三个参数,因为如果解构等式右边为 undefined 或 null 会发生程序错误。
const setCookieDefaults = {secure: false,path: "/",domain: "example.com",expires: new Date(Date.now() + 36000000)};function setCookie(name, value,{secure = setCookieDefaults.secure,path = setCookieDefaults.path,domain = setCookieDefaults.domain,expires = setCookieDefaults.expires} = setCookieDefault){//code}
先为第三个解构参数设定默认值,如果没有传入则默认为解构 setCookieDefaults。
然后设置解构值的默认值,若传入的第三个参数没有足够的属性,则会使用默认设置。