1、数组
let [a, b, c] = [1, 2, 3];
let [foo, [[bar], baz]] = [1, [[2], 3]; // foo = 1, bar = 2, baz = 3
let [x, y, ...z] = ['a']; // x = 'a', y = undefined, z = []
let [a, [b], d] = [1, [2, 3], 4]; // a = 1, b = 2, d = 4
数组的属性值严格等于undefined时,默认值才会生效,否则为数组属性值
let [x = 1] = [undefined]; // x = 1
let [x = 1] = [null]; // x = null
如果默认值是一个表达式,这个表达式只有用到时才会求值:
function f() {
console.log('aaa');
}
let [x = f()] = [1]; // 1,这里的x能直接取到1,所以函数f根本不会执行
2、对象的解构赋值
let {foo, bar} = { foo: "aaa", bar: "bbb"};
// 变量名与属性名不一致时
var { foo: baz } = { foo: 'aaa', bar: 'bbb' };
// baz: 'aaa', foo: foo is not defined; foo是匹配的模式,baz才是变量。
let { first: f, last: l } = { first: 'hello', last: 'world' };
// f: 'hello', l: 'world'
嵌套的对象的解构赋值:
var node = {
loc: {
start: {
line: 1,
column: 5
}
}
};
var {loc, loc: {start}, loc: {start: {line}}} = node;
console.log(loc, start, line);
// {start: {…}},start: {line: 1, column: 5}, 1
let obj = {
p: [
'hello',
{y: 'world'}
]
};
let {p, p: [x, {y}]} = obj;
console.log(p); // (2) ["hello", {y: "world}]
console.log(x); // "hello"
console.log(y); // "world"
对象的解构也可以制定默认值:
var {x = 3} = {};// x = 3
var {x, y = 5} = {x: 1};// x = 1 ,y = 5
var {x: y = 3} = {}; // y = 3
默认值生效的条件是,对象的属性严格等于undefined。
let arr = [1, 2, 3];
let {0: first, [arr.length - 1]: last} = arr; // []这种写法属于“属性名表达式”
console.log(first, last); // 1 3
3、用途
3.1 交换变量的值
let x= 1;
let y = 2;
[x, y] = [y, x];
3.2 从函数返回多个值,取值很方便
// 返回数组
function example() {
return [1, 2, 3];
}
let [a, b, c] = example();
console.log(a, b, c); // 1 2 3
// 返回对象
function example2() {
return {
foo: 1,
bar: 2
}
}
let {foo, bar} = example2();
console.log(foo, bar); // 1 2
3.3 函数参数的定义
function f([x, y, z]) {}
f([1,2,3]);
function f2({x, y, z}) {}
f2({z: 3, y: 2, x: 1});
3.4 提取JSON数据
let jsonData = {
id: 42,
status: 'ok',
data: [867, 5309]
};
let {id, status, data: number} = jsonData;
console.log(id, status, number); // 42 "ok" [867, 5309]
3.5 函数参数默认值
3.6 遍历Map
for (let [key, value] of map)
3.7导入模块时制定方法
[参考文献]:ES6标准入门(第三版)