解构可以帮助我们更好提取需要的对象中的数据,es6中可以使用新特性来更好的完成解构。
1. 对象解构
var car = {name:'baoma',color:'red'}
let {name,color} = car
// name :baoma
// color:red
//对象不能赋值为null或者undefiend
//TypeError: Cannot destructure property `type` of 'undefined' or 'null'.
解构的时候可以给解构的参数,重新命名,像这样,冒号后面就是对应的变量名
let {type:t} = {type:4}
console.log(t)
多重嵌套时的结构
// 多重嵌套 命名
// 这里 从a中取b命名为c
let {a:{b:c}} = {a:{
b:5
}}
console.log(c)
2. 数组解构
// 数组结构
let [color1,color2] = ['red','yellow']
console.log(color1,color2)
想要获取特定位置的元素的话,可以把特定位置空出来,像这样
let [,color2,color3] = ['red','yellow','blue']
同样,对于已经申明的变量,数组是这样解构的
//对于已经声明的变量
let color3 = 'red';
[color3] = ['blue']
console.log(color3)
数组中不定参数的解构
//不定参数的解构
let [first,...more]=[1,2,3,4,5];
console.log(first,more)
3. 举例
//交换两变量中的值,
let e=1,f=2;
[e,f] = [f,e];
console.log(e,f)
//克隆数组
let needCopyArray = [1,2]
let [...copyArray] = needCopyArray;
console.log(copyArray);
4.完整代码
// 不允许为空,或者undefined
//let { type } = null;
// 变量命名
let {type:t} = {type:4}
console.log(t)
// 多重嵌套 命名
let {a:{b:c}} = {a:{
b:5
}}
console.log(c)
// 数组结构
let [color1,color2] = ['red','yellow']
console.log(color1,color2)
//对于已经声明的变量
let color3 = 'red';
[color3] = ['blue']
console.log(color3)
//不定参数的解构
let [first,...more]=[1,2,3,4,5];
console.log(first,more)
//交换两变量中的值,
let e=1,f=2;
[e,f] = [f,e];
console.log(e,f)
//克隆数组
let needCopyArray = [1,2]
let [...copyArray] = needCopyArray;
console.log(copyArray);
// 数组结构
let [color1,color2] = ['red','yellow']
console.log(color1,color2)
//对于已经声明的变量
let color3 = 'red';
[color3] = ['blue']
console.log(color3)
//不定参数的解构
let [first,...more]=[1,2,3,4,5];
console.log(first,more)
//交换两变量中的值,
let e=1,f=2;
[e,f] = [f,e];
console.log(e,f)
//克隆数组
let needCopyArray = [1,2]
let [...copyArray] = needCopyArray;
console.log(copyArray);