数组/对象解构
// 数组的解构
const arr1 = [1, 2, 3];
let [a, b, c] = arr;
console.log(a, b, c); // 1 3 5
// 对象的解构
const obj = {
name: 'hello',
age: 12
}
let { name, age } = obj;
console.log(name, age); // hello 12
拓展:数组的解构
// 1、交换x和y的值
let [x, y] = [10, 20];
// 注意⚠️:let [x, y] = [10, 20];一定要写分号,否则会报错 Uncaught ReferenceError: Cannot access 'x' before initialization
// 这是因为js中,一般()和[]后一定要加分号,特别是与别人一起开发时,避免引起不必要的错误
// 分号也可以加在自己写的代码的前面,如 ;[x, y] = [y, x] 这样不管别人写的代码有没有加分号,都不会错
[x, y] = [y, x];
console.log(x, y); // 20 10
// 2、变量多,值少
const [a1, b1, c1] = ["vite", "pinia"];
console.log(a1); // vite
console.log(b1); // pinia
console.log(c1); // undefined
// 解决方案:给多出的变量赋予初始值
const [a2, b2, c2 = "dou"] = ["vite", "pinia"];
console.log(a2); // vite
console.log(b2); // pinia
console.log(c2); // dou
// 3、变量少,值多
// 解决方案:使用剩余参数
const [a3, ...b3] = ["vite", "pinia", "ts"];
console.log(a3); // vite
console.log(b3); // ['pinia', 'ts']
// 4、按需要导入,忽略某些值
const [a4, , c4] = ["vite", "pinia", "ts"];
// 忽略b4
console.log(a4); // vite
console.log(c4); // ts