解构-赋值
1. 数组解构
let first,second
[first, second] = [1, 2];
logd(first); // 输出: 1
logd(second); // 输出: 2
2. 稀 疏数组解构
let a,c
[a, , c] = [1, undefined, 3];
logd(a); // 输出: 1
logd(c); // 输出: 3
3. 字符串解构
let char1, char2
[char1, char2] = "ab";
logd(char1); // 输出: a
logd(char2); // 输出: b
4. 对象解构
- 需要在外层加
()
let name, age
({name, age} = {name: "Alice", age: 25})
logd(name); // 输出: Alice
logd(age); // 输出: 25
let c,d,e
({c, x:d, e} = {c:7, x:8})
logd(c,d,e) // 输出: 7, 8, undefined
5. 链式解构
- 数组
let a,b,c,d;
[a,b] = [c,d] = [1,2];
logd(a,b,c,d) // 输出: 1,2,1,2
- 对象
let a,b,c,d;
({a,b} = {c,d} = {a:1,b:2,c:3,d:4})
logd(a,b,c,d) // 输出: 1,2,3,4
6. 嵌套解构
let e, f, g, h, i;
[e, {x: f, g}] = [9, {x: 10}];
({h, x: [i]} = {h: 11, x: [12]});
logd(e, f, g, h, i) // 输出: 9, 10, undefined, 11, 12
8. 默认值
let a, b, c, d, e, f;
({a = 1, b = 0, z: c = 3} = {b: 2, z: undefined});
[d = 0, e = 5, f = 6] = [4, , undefined];
logd(a, b, c, d, e, f) // 输出: 1, 2, 3, 4, 5, 6