一、数组的解构赋值
例1:
let a = 10
b = a
console.log(b) //10
例2:
let [a, b] = [10, 20]
console.log(a); //10
console.log(b); //20
例3:
需求:交换a和b的值
let a = 10;
let b = 20;
let temp;
temp = a;
a = b;
b = temp;
console.log(a); //20
console.log(b); //10
例4:
数组的解构赋值的做法
let a = 10;
let b = 20;
[a, b] = [b, a];
console.log(a); //20
console.log(b); //10
二、对象的解构赋值
例1:
let {name, age} = {
name: '小红',
age: 12
}
console.log(name); //小红
console.log(age); //12
例2:
创建一个学生对象
function createStudent() {
let name = '小米';
let age = 23;
let friend = '小龙';
return {
name: name,
age: age,
friend: friend
}
}
let obj = createStudent();
console.log(obj); //{name: '小米', age: 23, friend: '小龙'}
es5写法,拿到obj的某一属性
console.log(obj.name); //小米
es6写法,不关心对象是什么,只想得到他的某一属性
let { name: username } = createStudent();
console.log(username); //小米