左右两边结构一样,声明和赋值不能分开必须要再同一行的代码里面
1、数组模型的解构
let arr = [1, 2, 3]; let a = arr[0]; let b = arr[1]; let c = arr[2]; console.log(a, b, c); // 1 ,2 ,3
let [a, b, c] = [1, 2, 3]; console.log(a, b, c); // 1 2 3
// 嵌套 let [a, [[b], c]] = [1, [[2], 3]]; console.log(a, b, c); // 1 2 3
// 忽略 let [a, , b] = [1, 2, 3]; console.log(a, b); // 1 3
// 不完全解构 let [a = 1, b] = []; console.log(a, b); // a = 1, b = undefined
// 剩余运算符 let {a, b, ...rest} = {a: 10, b: 20, c: 30, d: 40}; // a = 10 // b = 20 // rest = {c: 30, d: 40}
2、json解构
let {a, b, c} = {a: 1, b: 2, c: 3}; console.log(a, b, c); // 1 2 3
let [{a, b}, [n1, n2], num, str] = [{a: 1, b: 2}, [3, 4], 5, ‘6‘]; console.log(a, b, n1, n2, num, str); // 1 2 3 4 5 "6"
let [json, arr, num, str] = [{a: 1, b: 2}, [3, 4], 5, ‘6‘]; console.log(json, arr, num, str); // {a: 1, b: 2} (2) [3, 4] 5 "6"
3、解构,默认值
let {a = 10, b = 5} = {a: 3}; // a = 3; b = 5; let {a: aa = 10, b: bb = 5} = {a: 3}; // aa = 3; bb = 5;
当解构模式有匹配结果,且匹配结果是 undefined 时,会触发默认值作为返回结果。
let [a = 3, b = a] = []; // a = 3, b = 3 a 与 b 匹配结果为 undefined ,触发默认值:a = 3; b = a =3 let [a = 3, b = a] = [1]; // a = 1, b = 1 a 正常解构赋值,匹配结果:a = 1,b 匹配结果 undefined ,触发默认值:b = a =1 let [a = 3, b = a] = [1, 2]; // a = 1, b = 2 a 与 b 正常解构赋值,匹配结果:a = 1,b = 2
4、注意事项
// 左边为数组,右边为json,两边的结构不一样 let [a, b] = {a: 12, b: 34}; console.log(a, b); // 出错
// 右边类型错误,{12, 34} json写法错误 let {a, b} = {12, 34}; console.log(a, b); // Uncaught SyntaxError: Unexpected token
// 声明和赋值分开 let [a, b]; [a , b] = {12, 34}; console.log(a, b); // Uncaught SyntaxError: Missing initializer in destructuring declaration
原文:https://www.cnblogs.com/yangWanSheng/p/11710773.html