一、数组模型结构
1、基本
let [a, b, c] = [1, 2, 3];
output:
a = 1
b = 2
c = 3
2、可嵌套
let [a, [[b], c]] = [1, [[2], 3]];
output:
a = 1
b = 2
c = 3
3、可忽略
let [a, , b] = [1, 2, 3];
output:
a = 1
b = 3
4、不完全解构
let [a = 1, b] = [];
output:
a = 1, b = undefined
5、剩余运算符
let [a, ...b] = [1, 2, 3];
output:
a = 1
b = [2, 3]
6、字符串
let [a, b, c, d, e] = 'hello';
output:
a = 'h'
b = 'e'
c = 'l'
d = 'l'
e = 'o'
在数组的解构中,解构的目标若为可遍历对象,皆可进行解构赋值。
可遍历对象即实现 Iterator 接口的数据
7、解构默认值
let [a = 2] = [undefined];
output:
a = 2
二、对象模型Object解构
1、基本
let { foo, bar } = { foo: 'aaa', bar: 'bbb' };
output:
foo = 'aaa'
bar = 'bbb'
let { baz : foo } = { baz : 'ddd' };
output:
foo = 'ddd'
2、可嵌套可忽略
let obj = {p: ['hello', {y: 'world'}] };
let {p: [x, { y }] } = obj;
output:
x = 'hello'
y = 'world'
let obj = {p: ['hello', {y: 'world'}] };
let {p: [x, { }] } = obj;
output:
x = 'hello'
3、不完全解构
let obj = {p: [{y: 'world'}] };
let {p: [{ y }, x ] } = obj;
output:
x = undefined
y = 'world'
4、剩余运算符
let {a, b, ...rest} = {a: 10, b: 20, c: 30, d: 40};
output:
a = 10
b = 20
rest = {c: 30, d: 40}
5、解构默认值
let {a = 10, b = 5} = {a: 3};
output:
a = 3; b = 5;
let {a: aa = 10, b: bb = 5} = {a: 3};
output:
aa = 3; bb = 5;
参考:https://www.runoob.com/w3cnote/deconstruction-assignment.html