ES6 允许按照一定的模式, 从数组和对象中取值对变量进行赋值,被称为解构赋值
数组解构:
/*1.值和变量个数相同*/
let [a,b,c] = [1,2,3];//a,b,c是三个变量
console.log(a);//1
console.log(b);//2
console.log(c);//3
/*值和变量的个数不相同*/
let [x,y,z,p] = [5,6,7];
console.log(x);//5
console.log(y);//6
console.log(z);//7
console.log(p);//undefined
对象解构:
let person = { name:"张三",age:18,sex:"男"};
let { name,age,sex} = person;
/*1.变量名必须与属性名相同时:*/
console.log(name);//张三
console.log(age);//18
console.log(sex);//男
/*2.变量名与属性名不相同时*/
let user = { name:"李四",age:20,sex:"男",a:["爱吃","爱喝"]};
let {name:username,age:userage,sex:usersex,a:usera} = user;//username,userage,usersex属于别名
console.log(username);//李四
console.log(userage);//20
console.log(usersex);//男
console.log(usera[0]);//爱吃
字符串解构:
let [a,b] = "你好";
console.log(a);//你
console.log(b);//好