解构
ES6 允许按照一定模式,从数组和对象中提取值,对变量进行赋值,这被称为解构,解构的本质属于“模式匹配”,只要等号两边的模式相同,左边的变量就会被赋予对应的值。如果解构不成功,变量的值就等于undefined。
注意:
解构赋值等号右侧必须存在
等号右侧不是数组或者对象时,会先转换成对象,再继续操作。如果是 null、 undefined则抛出错误
数组解构
等号左边的变量放到中括号内部,匹配右侧数组中的元素
1.完全解构
let [a,b,c,d] = [1,2,3,4]
console.log(a,b,c,d); // 1 2 3 4
let [a,b,c,d,e] = [1,2,3,[4,5],6];
console.log(a,b,c,d,e); // 1 2 3 [ 4, 5 ] 6
2.不完全解构
let [a,b,c,[d],e]=[1,2,3,[4,5,6],7];
console.log(a,b,c,d,e); // 1 2 3 4 7
3.默认值解构
let [a=1,b=2,c=3]=[4,5,6];
console.log(a,b,c); // 4 5 6
let [a=1,b=2,c=3]=[];
console.log(a,b,c); // 1 2 3
默认值也可以是函数
function test(){console.log('hello')}
// let [a=test()]=[1];
// console.log(a); // 1
let [a=test()]=[];
console.log(a); // hello undefined
4.集合解构
let [a,...b]=[1,2,3,4,5];
console.log(a,b); // 1 [ 2, 3, 4, 5 ]
5.拓展运算符
let arr = [1,2,3,4,5]
let [...a] = arr;
console.log(arr); // [ 1, 2, 3, 4, 5 ]
console.log(a); // [ 1, 2, 3, 4, 5 ]
console.log(a==arr); // false
注意:拓展运算符用在左侧是聚合,用在右侧是展开。
let arr = [1,2,3,4];
// 拓展运算符用在左侧是聚合,用在右侧是展开
let [...a] = arr;
console.log(a); // [ 1, 2, 3, 4 ]
let obj = {name:"zzy", age:17}
let obj1 = {gender:"female"};
let temp = {
...obj,
...obj1,
}
console.log(temp); // { name: 'zzy', age: 17, gender: 'female' }
对象解构
等号左边的变量放到大括号内部,匹配右侧对象中的元素,对象的属性没有次序
1.属性名必须与变量名一致才能取到正确的值
let {name,age} = {name:"zzy", age:19}
console.log(name, age); // zzy 19
2.属性名与变量名不一致 给属性名重命名
let {name:a,age:b} = {name:"zzy", age:19}
console.log(a, b); // zzy 19
3.嵌套结构
let obj = {p:["hello",{y:"world"}]};
let {p:[h,{y:w}]} = obj;
console.log(h,w); // hello world
4.默认值结构
let {x:y=3}={};
console.log(y); // 3
经典面试题:
const [a, b, c, ...d] = [1, 2, 3, 11, 999];
const { e, f,f1, g, ...h } = { f: 4, g: 5, i: 6, j: 7 };
console.log(a, b, c, d, e, f1, g, h);
// 1 2 3 [ 11, 999 ] undefined undefined 5 { i: 6, j: 7 }
字符串解构
1.使用数组进行字符串解构
let [a,b,c,d,e] = "hello";
console.log(a,b,c,d,e); // h e l l o
2.使用拓展运算符解构
let [...arr] = "world";
console.log(arr); // [ 'w', 'o', 'r', 'l', 'd' ]
3.使用对象解构字符串
let {toString, valueOf, length} = 'hello'; //相当于把‘hello’当成String基本包装器类型
console.log(toString, valueOf, length); // [Function: toString] [Function: valueOf] 5
数值解构
可以获取到数值包装器构造函数原型中指定的方法。
let {toString,valueOf}=10;
console.log(toString,valueOf)
//[Function: toString] [Function: valueOf]
布尔值解构
let {toString,valueOf}=true;
console.log(toString,valueOf);
// [Function: toString] [Function: valueOf]
注意:
在解构赋值时,如果等号右边是数值或者布尔值,则会先转换成为对象,再进行赋值解构的规则:只要等号的右边不是对象或者数组,都会先将其转换成对象(注:undefined和null无法转换成对象,对其进行赋值时都会报错)