数组解构赋值
let [a, b, c] = [1, 2, 3];
let [foo, [[bar], baz]] = [1, [[2], 3]];foo // 1bar // 2baz // 3let [ , , third] = ["foo", "bar", "baz"];third // "baz"let [x, , y] = [1, 2, 3];x // 1y // 3let [head, ...tail] = [1, 2, 3, 4];head // 1tail // [2, 3, 4]let [x, y, ...z] = ['a'];x // "a"y // undefinedz // []
不完全解构
let [x, y] = [1, 2, 3];x // 1y // 2let [a, [b], d] = [1, [2, 3], 4];a // 1b // 2d // 4
如果等号的右边不是数组(严格地说,不是可遍历的结构),那么将会报错。
默认值
解构赋值允许指定默认值。
let [foo = true] = [];foo // truelet [x, y = 'b'] = ['a']; // x='a', y='b'let [x, y = 'b'] = ['a', undefined]; // x='a', y='b'let [x = 1, y = x] = []; // x=1; y=1let [x = y, y = 1] = []; // ReferenceError: y is not defined
ES6 内部使用严格相等运算符(===),判断一个位置是否有值
如果默认值是一个表达式,那么这个表达式是惰性求值的,即只有在用到的时候,才会求值。
function f() { console.log('aaa');}let [x = f()] = [1]; ///因为x能取到值,所以函数f根本不会执行
对象解构赋值
对象的解构与数组有一个重要的不同。数组的元素是按次序排列的,变量的取值由它的位置决定;而对象的属性没有次序,变量必须与属性同名,才能取到正确的值。
let { bar, foo } = { foo: "aaa", bar: "bbb" };foo // "aaa"bar // "bbb"let { baz } = { foo: "aaa", bar: "bbb" };baz // undefined//如果变量名与属性名不一致,必须写成下面这样let obj = { first: 'hello', last: 'world' };let { first: f, last: l } = obj;f // 'hello'l // 'world'first // undefined
如果要将一个已经声明的变量用于解构赋值,必须非常小心。
// 错误的写法let x;{x} = {x: 1};// SyntaxError: syntax error// 正确的写法let x;({x} = {x: 1});
由于数组本质是特殊的对象,因此可以对数组进行对象属性的解构。
let arr = [1, 2, 3];let {0 : first, [arr.length - 1] : last} = arr;first // 1last // 3
字符串解构赋值
字符串也可以解构赋值。这是因为此时,字符串被转换成了一个类似数组的对象。
const [a, b, c, d, e] = 'hello';a // "h"b // "e"c // "l"d // "l"e // "o"let {length : len} = 'hello';len // 5
数值和布尔值解构赋值
解构赋值的规则是,只要等号右边的值不是对象或数组,就先将其转为对象。
let {toString: s} = 123;s === Number.prototype.toString // truelet {toString: s} = true;s === Boolean.prototype.toString // true
函数参数解构赋值
function add([x, y]){ return x + y;}add([1, 2]); // 3
函数add的参数表面上是一个数组,但在传入参数的那一刻,数组参数就被解构成变量x和y。
//默认值function move({x = 0, y = 0} = {}) { return [x, y];}move({x: 3, y: 8}); // [3, 8]move({x: 3}); // [3, 0]move({}); // [0, 0]move(); // [0, 0]