数组
机制
对数组进行“模式匹配”,只要等号两边的模式相同,左边的变量就会被赋予对应的值。
let [a,b,c] = [1,2,3]console.log(a,b,c) // 1 2 3
let [,,c] = [1,2,3]console.log(c) // 3
let [a,,c] = [1,2,3]console.log(a,c) // 1 3
let [a, ...b] = [1, 2, 3, 4];console.log(a) // 1console.log(b) // [2, 3, 4]
解构不成功时,会赋值
undefinedlet [a] = []console.log(a) // undefined
默认值
当对应值
=== undefind时,会选择默认值let [a = 1, b = 1] = [];console.log(a,b) // 1 1
let [a = 1, b = 1] = [null];console.log(a,b) // null 1
let [a = 1, b = 1] = [2,2];console.log(a,b) // 2 2
默认值可以引用解构赋值的其他变量,但该变量必须已经声明。
let [x = 1, y = x] = []; // x=1; y=1let [x = 1, y = x] = [2]; // x=2; y=2let [x = 1, y = x] = [1, 2]; // x=1; y=2let [x = y, y = 1] = []; // ReferenceError: y is not defined
对象
机制
先找到同名属性,然后再赋给对应的变量。真正被赋值的是后者,而不是前者。
let { a: foo, b: bar } = { a: 'aaa', b: 'bbb' };// foo、bar 才是赋值的对象
不按数据顺序进行复制,变量名需相同
let { b, a } = { a: 'aaa', b: 'bbb' };console.log(a) // "aaa"console.log(b) // "bbb"
多次解构 ```javascript const node = { loc: { start: {
line: 1,column: 5
} } };
let { loc, loc: { start }, loc: { start: { line }} } = node; console.log(line) // 1 console.log(loc) // Object {start: Object} console.log(start) // Object {line: 1, column: 5}
- 重复赋值:- 对象解构形式允许多次列出同一个源属性(持有值类型任意)。- 这也意味着可以解构子对象 / 数组属性,同时捕获子对象 / 类的值本身。```javascriptvar { a: { x: X, x: Y }, a } = { a: { x: 1 } };X; // 1Y; // 1a; // { x: 1 }( { a: X, a: Y, a: [ Z ] } = { a: [ 1 ] } ); X.push( 2 ); Y[0] = 10;X; // [10,2]Y; // [10,2]Z; // 1
默认值
- 当对应值
=== undefind时,会选择默认值 ```javascript var {x = 3} = {}; x // 3
var {x: y = 3} = {}; y // 3
var {x: y = 3} = {x: 5}; y // 5
var { message: msg = ‘Something went wrong’ } = {}; msg // “Something went wrong”
<a name="o6Rrv"></a>### 数组解构为对象- 由于数组本质是特殊的对象,因此可以对数组进行对象属性的解构。```javascriptlet arr = [1, 2, 3];let {0 : a, 1 : b, [arr.length - 1] : c} = arr;console.log(a) // 1console.log(b) // 2console.log(c) // 3
字符串
字符串也可以解构赋值。这是因为此时,字符串被转换成了一个类似数组的对象。
const [a, b, c, d, e] = 'hello';console.log(a,b,c,d,e) // h e l l o
类似数组的对象都有一个
length属性,因此还可以对这个属性解构赋值。let {length : len} = 'hello';consloe.log(len) // 5
函数参数
const fn = ({a = 1,b = 2} = {}) => {return [a,b]}fn({}) // [1,2]fn({a:x,b:y}) // [x,y]fn() // [1, 2]
下面的写法会得到不一样的结果。
function move({a, b} = { a: 0, b: 0 }) {return [a, b];}move({a: 3, b: 8}); // [3, 8]move({a: 3}); // [3, undefined]move({}); // [undefined, undefined]move(); // [0, 0]
交换变量
let x = 1;let y = 2;[x, y] = [y, x];
导入模块
const { SourceMapConsumer, SourceNode } = require("source-map");
