1⃣️ 数组解构
let arr = [1, 2, 3]
let [a, b, c] = arr;
console.log(a, b, c) // 1 2 3
let arr = [1, 2, [3, 4]]
let [a, b, c] = arr;
console.log(a, b, c) // 1 2 [3,4]
let arr = [1, 2, [3, 4]]
let [a, b, [c, d]] = arr;
console.log(a, b, c, d) // 1 2 3,4
let [a, b, c, d] = [1, 2, [3, 4]];
console.log(a, b, c, d) // 1 2 [3, 4] undefined
let [a, b, c, d = 5] = [1, 2, [3, 4]];
console.log(a, b, c, d) // 1 2 [3, 4] 5
let [a, b, c, d = 5] = [1, 2, [3, 4], 6];
console.log(a, b, c, d) // 1 2 [3, 4] 6
2⃣️对象解构
let user = {
name: 'kiw',
age: '18'
}
let {
name,
age
} = user
console.log(name, age) // kiw 18
别名
let user = {
name: 'kiw',
age: '18'
}
let {
name: uname,
age: uage
} = user
console.log(uname, uage) // kiw 18
3⃣️字符串解构
let str = 'imooc'
let [a, b, c, d, e] = str;
console.log(a, b, c, d, e); // i m o o c
作用
1利用解构实现 默认值 和快速赋值/传值
2 快速提取对象/数组中的一些属性 减少代码量
网友评论