1、解构:按照一定模式,从数组和对象中提取值,对变量进行赋值(严格来说是具有Iterator的某种数据结构)。(解构赋值属于浅拷贝)
2、基本用法:模式匹配,等号两边模式一样就会赋值
1)数组
let [a,b,c]=[1,2,3]
//a=1
//b=2
//c=3
let [a,b,c]=[1,2,]
//a=1
//b=2
//c=undefined
let [a,,c]=[1,2,3]
//a=1
//c=3
let [a,...b]=[1,2,3]
//a=1
//b=[2,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
2)对象(根据对应的属性名匹配,如果没有则为undefined)
let { foo, bar } = { foo: 'aaa', bar: 'bbb' };
foo // "aaa"
bar // "bbb"
let { baz } = { foo: 'aaa', bar: 'bbb' };
baz // undefined
const { log } = console;
log('hello') // hello
//赋值的是变量,此时foo事模式
let { foo: baz } = { foo: 'aaa', bar: 'bbb' };
baz // "aaa"
foo // error: foo is not defined
let obj = {
p: [
'Hello',
{ y: 'World' }
]
};
let { p, p: [x, { y }] } = obj;
x // "Hello"
y // "World"
p // ["Hello", {y: "World"}]
3)字符串解构赋值(优先转为对象)
let {length : len} = 'hello';//相当于在‘length'这个类数组对象中寻找雨’length‘同名的属性赋值
len // 5
const [a, b, c, d, e] = 'hello';
a // "h"
b // "e"
c // "l"
d // "l"
e // "o"
4)数值和布尔值的解构赋值(优先转为对象)
let {toString: s} = 123;
s === Number.prototype.toString // true
let {toString: s} = true;
s === Boolean.prototype.toString // true
5)函数参数的解构赋值
function move({x = 0, y = 0} = {}) {
return [x, y];
}
move({x: 3, y: 8}); // [3, 8]
move({x: 3}); // [3, 0]
move({}); // [0, 0]
move(); // [0, 0]
function move({x, y} = { x: 0, y: 0 }) {
return [x, y];
}
move({x: 3, y: 8}); // [3, 8]
move({x: 3}); // [3, undefined]
move({}); // [undefined, undefined]
move(); // [0, 0]
//以上两者的区别在于第一种将值赋给了参数,第二种将参数作为一个对象统一赋值,所以只用在参数对象为undefined时才取默认值
[[1, 2], [3, 4]].map(([a, b]) => a + b);
// [ 3, 7 ]
3、默认值(当一个元素解构获得的值严格等于(===)undefined,默认值才生效)
let [foo = true] = [];
foo // true
let [x, y = 'b'] = ['a']; // x='a', y='b'
let [x, y = 'b'] = ['a', undefined]; // x='a', y='b'
//当默认值为表达式时,只有当解构的值为undefined时才会执行
function fu(){
return 31}
let [a=fu()]=[3]//3,且fu不执行
let [a=fu()]=[]//31,且fu()执行