对象解构
解构声明
解构声明时必须初始化,且=右侧的值不能是null或undefined,否则报错。
let node = {
type: "Identifier",
name: "foo",
age: 20,
};
// 解构声明
let {type,name,age} = node;
解构赋值
解构赋值时要用小括号包裹,因为js引擎将一对花括号视为一个代码块,代码块是不允许出现在赋值语句左侧的,添加小括号后可以将代码块转换为一个表达式。
({type,name,age} = node)
默认值
如果解构的变量名不存在,会被赋值为 undefined。如果我们不希望出现 undefined,可以给解构后的变量添加默认值。
let {type,name,value = true} = node;
非同名属性解构
let {type: localType,name: localName = 'bar' } = node;
嵌套对象解构
let node = {
loc: {
start: { line: 1, column: 1 },
}
};
//很像非同名属性解构的,当:后面的是变量名时,则是为这个对象中的属性重新命名;
//当后面是{}时,则要进一步去:前的对象中更深层次去找
let { loc: { start } }= node;
数组解构
解构声明
在数组解构中,我们是通过值在数组中的位置进行选取的,未显示声明的元素都会被忽略。
let colors= [ "red","green","blue" ];
let [ firstColor="yellow", secondColor ]= colors;
let [ ,, thirdColor ]= colors;
解构赋值
不需要用小括号包裹
[ firstColo, secondColor ] = node
交换两个变量的值
let a = 1, b = 2;
// 左侧是解构语法,右侧是一个数组字面量
[a, b] = [b, a]
嵌套数组解构
let colors= [ "red", [ "green", "lightgreen"], "blue"];
let [ firstColor, [ ,secondColor] ] = colors;
不定元素
let colors= [ "red","green","blue" ];
// 不定元素的用法
let [ firstColor, ...restColors ] = colors
// 可以利用不定元素进行数组复制,cloneColors 就是 colors 的一个副本
let [ ...cloneColors ] = colors
混合解构
let node = {
loc: {
start: { line: 1, column: 1 }
},
range: [0, 3]
};
let {
loc: {start},
range: [startIndex]
} = node;
解构参数
用解构的方法定义对象,可以更清晰的表示函数预期传入的参数
function setCookie(name, value, { secure,path,domain,expires }) { ... }
setCookie("type", "js", {
secure: true,
expires: 60000
});
但是解构的语法中,右侧的值不能是null或undefined,否则报错,而解构参数的语法只是将解构声明应用到函数参数的一个简写,所以需要给参数赋默认值。
function setCookie(name, value, { secure,path,domain,expires } = {}) { ... }
如果需要给解构中的每一项赋默认值,则需要这样写:
const setCookieDefaults = {
secure = false,
path = "/",
domain = "example. com ",
expires = new Date(Date.now() + 360000000)
}
function setCookie(name, value, {
secure = setCookieDefaults.secure,
path = setCookieDefaults.path,
domain = setCookieDefaults.domain,
expires = setCookieDefaults.expires
} = setCookieDefaults) { ... }