数组解构
数组解构是将数组的单元值快速批量赋值给一系列变量的简洁语法
let arr = [1, 2, 3];
let [a, b, c] = arr;
let [a, b, c] = [1, 2, 3];
console.log(a);
console.log(b);
console.log(c);
let [a, b, c, d, e, f] = [1, 2, 3];
console.log(a);
console.log(b);
console.log(c);
let [a, b, c] = [1, 2, 3, 4, 5];
console.log(a);
console.log(b);
console.log(c);
let [a, , b, , c] = [1, 2, 3, 4, 5];
console.log(a);
console.log(b);
console.log(c);
let [a, b, ...c] = [1, 2, 3, 4, 5];
console.log(a);
console.log(b);
console.log(c);
let arr = [1, 2, 3, [4, 5, 6]];
let [a, , b, [, c]] = arr;
console.log(a, b, c);
一一对应!!!!
对象解构
let uname = "xixi";
let { age, uname: username } = {
uname: "haha",
age: "19",
sex: "男",
};
console.log(age, uname);
let {dog:{name,age}}={
uname: "haha",
age: "19",
sex: "男",
dog:{
name:'da',
age:'1',
},
cat:{
name='xiao',
age:'12'
}
}
注意:
- 赋值运算符
= 左侧的 {} 用于批量声明变量,右侧对象的属性值将被赋值给左侧的变量 - 对象属性的值将被赋值给与属性名相同的变量
- 对象中找不到与变量名一致的属性时变量值为
undefined - 允许初始化变量的默认值,属性不存在或单元值为
undefined 时默认值才会生效
|