1、数组解构
let [a, b, c] = [1, 2, 3];
// 报错
let [foo] = 1;
let [foo] = false;
let [foo] = NaN;
let [foo] = undefined;
let [foo] = null;
let [foo] = {};
如果等号的右边不是数组,将会报错
2、对象的结构
let { foo, bar } = { foo: ‘aaa’, bar: ‘bbb’ };
foo // “aaa”
bar // “bbb”
数组的结构与对象的结构又一个重要的不同。数组的结构是按次序和位置来决定的取值,但是对象的结构与位置没有关系,变量必须与属性相同,才能去到正确的值。
let { bar, foo } = { foo: ‘aaa’, bar: ‘bbb’ };
foo // “aaa”
bar // “bbb”
let { baz } = { foo: ‘aaa’, bar: ‘bbb’ };
baz // undefined
实际上对象结构是let { foo: foo, bar: bar } = { foo: ‘aaa’, bar: ‘bbb’ };的简写
3、字符串的结构
const [a, b, c, d, e] = ‘hello’;
a // “h”
b // “e”
c // “l”
d // “l”
e // “o”
let {length : len} = ‘hello’;
len // 5
4、数值和布尔值的结构
如果等好右边是数值和布尔值,则会先转化为对象
let {toString: s} = 123;
s === Number.prototype.toString // true
let {toString: s} = true;
s === Boolean.prototype.toString // true
5、函数参数的结构赋值
函数的参数也可以进行结构赋值
function add([x, y]){
return x + y;
}
add([1, 2]); // 3
[[1, 2], [3, 4]].map(([a, b]) => a + b);
// [ 3, 7 ]