解构赋值:按照一定模式从数组和对象中提取值对变量进行赋值。
一、数组解构
数组解构赋值时按照索引进行对应赋值,要注意顺序
(1)一维数组
let arr = [1,2,3];
let [a,b,c] = arr;
console.log(a,b,c);//1,2,3
(2)二维数组
let arr = [1,2,[3,4]];
let [a,b,c] = arr;
console.log(a,b,c);//1 2 (2) [3, 4]
let arr = [1,2,[3,4]];
let [a,b,[c]] = arr;
console.log(a,b,c);//1 2 3
(3)左侧接受的变量在右边没有对应的
let arr = [1,2,[3,4]];
let [a,b,[c],d] = arr;
console.log(a,b,c,d);//1 2 3 undefined
(4)设置默认值
let arr = [1,2,[3,4]];
let [a,b,[c],d = 5] = arr;
console.log(a,b,c,d);//1 2 3 5
二、对象解构
按照对象的键赋值,顺序随意
(1)
let hero = {
name:"Asia",
age:23
}
let {name,age} = hero;
console.log(name,age);//Asia 23
左侧换顺序
let hero = {
name:"Asia",
age:23
}
let {age,name} = hero;
console.log(name,age);//Asia 23
(2) 定义别名
let hero = {
name:"Asia",
age:23
}
let {age:age2,name:name2} = hero;
console.log(name2,age2);//Asia 23
三、字符串解构赋值
和数组一样按照顺序解构
let str = "面对疾风吧!哈撒给!"
let [a,b,c,d,e,f,g,h,i,j,k,l,m,n] = str;
console.log(a,b,c,d,e,f,g,h,i,j,k,l,m,n);//面 对 疾 风 吧 ! 哈 撒 给 ! undefined undefined undefined undefined
四、函数参数解构赋值
function fn([a,b,c]){
console.log(a,b,c);
}
fn([1,2,3]);//1 2 3
五、JSON解构赋值
let json = '{"name":"Asia","age":20}';
let {name,age} = JSON.parse(json);
console.log(name,age);//Asia 20