const obj ={
name:"111",
age:12,
sex:0,
address:{
x:"abc",
y:"cde"}}//正常// let name,age,sex,address;// name = obj.name;// age = obj.age;// sex = obj.sex;// address = obj.address;//解构// let name,age,sex,address;// ( { name , age , sex , address } = obj );//简写解构,先定义4个变量,然后从对象中读取同名属性,放到变量中let{ name , age , sex , address }= obj;
console.log(name,age,sex,address);
const obj ={
name:"111",
address:{
x:"abc",
y:"cde"}}//先定义两个变量name,xlet{ name , address:{ x }}= obj;
console.log(name,x);//111 abc
数组解构
数组本质还是对象
//变量名在后const numbers =['a','b','c','d']const{0:n1,1:n2,2:n3,3:n4}= numbers;const{0:n1,1:n2,2:n3,3:n4,4:n5}= numbers;
console.log(n1,n2,n3,n4);//结果一样 a b c d
更加方便
const numbers =['a','b','c','d'];const[n1,n2,n3,n4]= numbers;
console.log(n1,n2,n3,n4);//a b c d
还可以跳着写,中间空格
const numbers =['a','b','c','d']const[n1,,, n4]= numbers;
console.log(n1,n4);//a d