ES6入门之变量的解构赋值

1. 数组的解构赋值

基本用法

ES6 容许按照必定模式,从数组和对象中提取值,对变量进行赋值,这被称为解构(Destructuring)。javascript

之前,为变量赋值,只能直接指定值。java

let a = 1; let b = 2; let c = 3; let a = 1; let b = 2; let c = 3;

ES6 容许写成下面这样。node

let [a, b, c] = [1, 2, 3]; let [a, b, c] = [1, 2, 3];

上面代码表示,能够从数组中提取值,按照对应位置,对变量赋值。es6

本质上,这种写法属于“模式匹配”,只要等号两边的模式相同,左边的变量就会被赋予对应的值。下面是一些使用嵌套数组进行解构的例子。ajax

let [foo, [[bar], baz]] = [1, [[2], 3]]; foo // 1 bar // 2 baz // 3  let [ , , third] = ["foo", "bar", "baz"]; third // "baz"  let [x, , y] = [1, 2, 3]; x // 1 y // 3  let [head, ...tail] = [1, 2, 3, 4]; head // 1 tail // [2, 3, 4]  let [x, y, ...z] = ['a']; x // "a" y // undefined z // [] let [foo, [[bar], baz]] = [1, [[2], 3]]; foo // 1 bar // 2 baz // 3  let [ , , third] = ["foo", "bar", "baz"]; third // "baz"  let [x, , y] = [1, 2, 3]; x // 1 y // 3  let [head, ...tail] = [1, 2, 3, 4]; head // 1 tail // [2, 3, 4]  let [x, y, ...z] = ['a']; x // "a" y // undefined z // [] 

若是解构不成功,变量的值就等于undefinedjson

let [foo] = []; let [bar, foo] = [1]; let [foo] = []; let [bar, foo] = [1];

以上两种状况都属于解构不成功,foo的值都会等于undefined数组

另外一种状况是不彻底解构,即等号左边的模式,只匹配一部分的等号右边的数组。这种状况下,解构依然能够成功。数据结构

let [x, y] = [1, 2, 3]; x // 1 y // 2  let [a, [b], d] = [1, [2, 3], 4]; a // 1 b // 2 d // 4 let [x, y] = [1, 2, 3]; x // 1 y // 2  let [a, [b], d] = [1, [2, 3], 4]; a // 1 b // 2 d // 4 

上面两个例子,都属于不彻底解构,可是能够成功。async

若是等号的右边不是数组(或者严格地说,不是可遍历的结构,参见《Iterator》一章),那么将会报错。函数

// 报错 let [foo] = 1; let [foo] = false; let [foo] = NaN; let [foo] = undefined; let [foo] = null; let [foo] = {}; // 报错 let [foo] = 1; let [foo] = false; let [foo] = NaN; let [foo] = undefined; let [foo] = null; let [foo] = {};

上面的语句都会报错,由于等号右边的值,要么转为对象之后不具有 Iterator 接口(前五个表达式),要么自己就不具有 Iterator 接口(最后一个表达式)。

对于 Set 结构,也可使用数组的解构赋值。

let [x, y, z] = new Set(['a', 'b', 'c']); x // "a" let [x, y, z] = new Set(['a', 'b', 'c']); x // "a" 

事实上,只要某种数据结构具备 Iterator 接口,均可以采用数组形式的解构赋值。

function* fibs() { let a = 0; let b = 1; while (true) { yield a; [a, b] = [b, a + b]; } } let [first, second, third, fourth, fifth, sixth] = fibs(); sixth // 5 function* fibs() { let a = 0; let b = 1; while (true) { yield a; [a, b] = [b, a + b]; } } let [first, second, third, fourth, fifth, sixth] = fibs(); sixth // 5 

上面代码中,fibs是一个 Generator 函数(参见《Generator 函数》一章),原生具备 Iterator 接口。解构赋值会依次从这个接口获取值。

默认值

解构赋值容许指定默认值。

let [foo = true] = []; foo // true  let [x, y = 'b'] = ['a']; // x='a', y='b' let [x, y = 'b'] = ['a', undefined]; // x='a', y='b' let [foo = true] = []; foo // true  let [x, y = 'b'] = ['a']; // x='a', y='b' let [x, y = 'b'] = ['a', undefined]; // x='a', y='b' 

注意,ES6 内部使用严格相等运算符(===),判断一个位置是否有值。因此,只有当一个数组成员严格等于undefined,默认值才会生效。

let [x = 1] = [undefined]; x // 1  let [x = 1] = [null]; x // null let [x = 1] = [undefined]; x // 1  let [x = 1] = [null]; x // null 

上面代码中,若是一个数组成员是null,默认值就不会生效,由于null不严格等于undefined

若是默认值是一个表达式,那么这个表达式是惰性求值的,即只有在用到的时候,才会求值。

function f() { console.log('aaa'); } let [x = f()] = [1]; function f() { console.log('aaa'); } let [x = f()] = [1];

上面代码中,由于x能取到值,因此函数f根本不会执行。上面的代码其实等价于下面的代码。

let x; if ([1][0] === undefined) { x = f(); } else { x = [1][0]; } let x; if ([1][0] === undefined) { x = f(); } else { x = [1][0]; }

默认值能够引用解构赋值的其余变量,但该变量必须已经声明。

let [x = 1, y = x] = [];  // x=1; y=1 let [x = 1, y = x] = [2];  // x=2; y=2 let [x = 1, y = x] = [1, 2]; // x=1; y=2 let [x = y, y = 1] = [];  // ReferenceError: y is not defined let [x = 1, y = x] = [];  // x=1; y=1 let [x = 1, y = x] = [2];  // x=2; y=2 let [x = 1, y = x] = [1, 2]; // x=1; y=2 let [x = y, y = 1] = [];  // ReferenceError: y is not defined 

上面最后一个表达式之因此会报错,是由于xy作默认值时,y尚未声明。

2. 对象的解构赋值

解构不只能够用于数组,还能够用于对象。

let { foo, bar } = { foo: "aaa", bar: "bbb" }; foo // "aaa" bar // "bbb" let { foo, bar } = { foo: "aaa", bar: "bbb" }; foo // "aaa" bar // "bbb" 

对象的解构与数组有一个重要的不一样。数组的元素是按次序排列的,变量的取值由它的位置决定;而对象的属性没有次序,变量必须与属性同名,才能取到正确的值。

let { bar, foo } = { foo: "aaa", bar: "bbb" }; foo // "aaa" bar // "bbb"  let { baz } = { foo: "aaa", bar: "bbb" }; baz // undefined let { bar, foo } = { foo: "aaa", bar: "bbb" }; foo // "aaa" bar // "bbb"  let { baz } = { foo: "aaa", bar: "bbb" }; baz // undefined 

上面代码的第一个例子,等号左边的两个变量的次序,与等号右边两个同名属性的次序不一致,可是对取值彻底没有影响。第二个例子的变量没有对应的同名属性,致使取不到值,最后等于undefined

若是变量名与属性名不一致,必须写成下面这样。

let { foo: baz } = { foo: 'aaa', bar: 'bbb' }; baz // "aaa"  let obj = { first: 'hello', last: 'world' }; let { first: f, last: l } = obj; f // 'hello' l // 'world' let { foo: baz } = { foo: 'aaa', bar: 'bbb' }; baz // "aaa"  let obj = { first: 'hello', last: 'world' }; let { first: f, last: l } = obj; f // 'hello' l // 'world' 

这实际上说明,对象的解构赋值是下面形式的简写(参见《对象的扩展》一章)。

let { foo: foo, bar: bar } = { foo: "aaa", bar: "bbb" }; let { foo: foo, bar: bar } = { foo: "aaa", bar: "bbb" };

也就是说,对象的解构赋值的内部机制,是先找到同名属性,而后再赋给对应的变量。真正被赋值的是后者,而不是前者。

let { foo: baz } = { foo: "aaa", bar: "bbb" }; baz // "aaa" foo // error: foo is not defined let { foo: baz } = { foo: "aaa", bar: "bbb" }; baz // "aaa" foo // error: foo is not defined 

上面代码中,foo是匹配的模式,baz才是变量。真正被赋值的是变量baz,而不是模式foo

与数组同样,解构也能够用于嵌套结构的对象。

let obj = { p: [ 'Hello', { y: 'World' } ] }; let { p: [x, { y }] } = obj; x // "Hello" y // "World" let obj = { p: [ 'Hello', { y: 'World' } ] }; let { p: [x, { y }] } = obj; x // "Hello" y // "World" 

注意,这时p是模式,不是变量,所以不会被赋值。若是p也要做为变量赋值,能够写成下面这样。

let obj = { p: [ 'Hello', { y: 'World' } ] }; let { p, p: [x, { y }] } = obj; x // "Hello" y // "World" p // ["Hello", {y: "World"}] let obj = { p: [ 'Hello', { y: 'World' } ] }; let { p, p: [x, { y }] } = obj; x // "Hello" y // "World" p // ["Hello", {y: "World"}] 

下面是另外一个例子。

const node = { loc: { start: { line: 1, column: 5 } } }; let { loc, loc: { start }, loc: { start: { line }} } = node; line // 1 loc  // Object {start: Object} start // Object {line: 1, column: 5} const node = { loc: { start: { line: 1, column: 5 } } }; let { loc, loc: { start }, loc: { start: { line }} } = node; line // 1 loc  // Object {start: Object} start // Object {line: 1, column: 5} 

上面代码有三次解构赋值,分别是对locstartline三个属性的解构赋值。注意,最后一次对line属性的解构赋值之中,只有line是变量,locstart都是模式,不是变量。

下面是嵌套赋值的例子。

let obj = {}; let arr = []; ({ foo: obj.prop, bar: arr[0] } = { foo: 123, bar: true }); obj // {prop:123} arr // [true] let obj = {}; let arr = []; ({ foo: obj.prop, bar: arr[0] } = { foo: 123, bar: true }); obj // {prop:123} arr // [true] 

对象的解构也能够指定默认值。

var {x = 3} = {}; x // 3  var {x, y = 5} = {x: 1}; x // 1 y // 5  var {x: y = 3} = {}; y // 3  var {x: y = 3} = {x: 5}; y // 5  var { message: msg = 'Something went wrong' } = {}; msg // "Something went wrong" var {x = 3} = {}; x // 3  var {x, y = 5} = {x: 1}; x // 1 y // 5  var {x: y = 3} = {}; y // 3  var {x: y = 3} = {x: 5}; y // 5  var { message: msg = 'Something went wrong' } = {}; msg // "Something went wrong" 

默认值生效的条件是,对象的属性值严格等于undefined

var {x = 3} = {x: undefined}; x // 3  var {x = 3} = {x: null}; x // null var {x = 3} = {x: undefined}; x // 3  var {x = 3} = {x: null}; x // null 

上面代码中,属性x等于null,由于nullundefined不严格相等,因此是个有效的赋值,致使默认值3不会生效。

若是解构失败,变量的值等于undefined

let {foo} = {bar: 'baz'}; foo // undefined let {foo} = {bar: 'baz'}; foo // undefined 

若是解构模式是嵌套的对象,并且子对象所在的父属性不存在,那么将会报错。

// 报错 let {foo: {bar}} = {baz: 'baz'}; // 报错 let {foo: {bar}} = {baz: 'baz'};

上面代码中,等号左边对象的foo属性,对应一个子对象。该子对象的bar属性,解构时会报错。缘由很简单,由于foo这时等于undefined,再取子属性就会报错,请看下面的代码。

let _tmp = {baz: 'baz'}; _tmp.foo.bar // 报错 let _tmp = {baz: 'baz'}; _tmp.foo.bar // 报错 

若是要将一个已经声明的变量用于解构赋值,必须很是当心。

// 错误的写法 let x; {x} = {x: 1}; // SyntaxError: syntax error // 错误的写法 let x; {x} = {x: 1}; // SyntaxError: syntax error 

上面代码的写法会报错,由于 JavaScript 引擎会将{x}理解成一个代码块,从而发生语法错误。只有不将大括号写在行首,避免 JavaScript 将其解释为代码块,才能解决这个问题。

// 正确的写法 let x; ({x} = {x: 1}); // 正确的写法 let x; ({x} = {x: 1});

上面代码将整个解构赋值语句,放在一个圆括号里面,就能够正确执行。关于圆括号与解构赋值的关系,参见下文。

解构赋值容许等号左边的模式之中,不放置任何变量名。所以,能够写出很是古怪的赋值表达式。

({} = [true, false]); ({} = 'abc'); ({} = []); ({} = [true, false]); ({} = 'abc'); ({} = []);

上面的表达式虽然毫无心义,可是语法是合法的,能够执行。

对象的解构赋值,能够很方便地将现有对象的方法,赋值到某个变量。

let { log, sin, cos } = Math; let { log, sin, cos } = Math;

上面代码将Math对象的对数、正弦、余弦三个方法,赋值到对应的变量上,使用起来就会方便不少。

因为数组本质是特殊的对象,所以能够对数组进行对象属性的解构。

let arr = [1, 2, 3]; let {0 : first, [arr.length - 1] : last} = arr; first // 1 last // 3 let arr = [1, 2, 3]; let {0 : first, [arr.length - 1] : last} = arr; first // 1 last // 3 

上面代码对数组进行对象解构。数组arr0键对应的值是1[arr.length - 1]就是2键,对应的值是3。方括号这种写法,属于“属性名表达式”(参见《对象的扩展》一章)。

3. 字符串的解构赋值

字符串也能够解构赋值。这是由于此时,字符串被转换成了一个相似数组的对象。

const [a, b, c, d, e] = 'hello'; a // "h" b // "e" c // "l" d // "l" e // "o" const [a, b, c, d, e] = 'hello'; a // "h" b // "e" c // "l" d // "l" e // "o" 

相似数组的对象都有一个length属性,所以还能够对这个属性解构赋值。

let {length : len} = 'hello'; len // 5 let {length : len} = 'hello'; len // 5 

4. 数值和布尔值的解构赋值

解构赋值时,若是等号右边是数值和布尔值,则会先转为对象。

let {toString: s} = 123; s === Number.prototype.toString // true  let {toString: s} = true; s === Boolean.prototype.toString // true let {toString: s} = 123; s === Number.prototype.toString // true  let {toString: s} = true; s === Boolean.prototype.toString // true 

上面代码中,数值和布尔值的包装对象都有toString属性,所以变量s都能取到值。

解构赋值的规则是,只要等号右边的值不是对象或数组,就先将其转为对象。因为undefinednull没法转为对象,因此对它们进行解构赋值,都会报错。

let { prop: x } = undefined; // TypeError let { prop: y } = null; // TypeError let { prop: x } = undefined; // TypeError let { prop: y } = null; // TypeError 

5. 函数参数的解构赋值

函数的参数也可使用解构赋值。

function add([x, y]){ return x + y; } add([1, 2]); // 3 function add([x, y]){ return x + y; } add([1, 2]); // 3 

上面代码中,函数add的参数表面上是一个数组,但在传入参数的那一刻,数组参数就被解构成变量xy。对于函数内部的代码来讲,它们能感觉到的参数就是xy

下面是另外一个例子。

[[1, 2], [3, 4]].map(([a, b]) => a + b); // [ 3, 7 ] [[1, 2], [3, 4]].map(([a, b]) => a + b); // [ 3, 7 ] 

函数参数的解构也可使用默认值。

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] 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] 

上面代码中,函数move的参数是一个对象,经过对这个对象进行解构,获得变量xy的值。若是解构失败,xy等于默认值。

注意,下面的写法会获得不同的结果。

function move({x, y} = { x: 0, y: 0 }) { return [x, y]; } move({x: 3, y: 8}); // [3, 8] move({x: 3}); // [3, undefined] move({}); // [undefined, undefined] move(); // [0, 0] function move({x, y} = { x: 0, y: 0 }) { return [x, y]; } move({x: 3, y: 8}); // [3, 8] move({x: 3}); // [3, undefined] move({}); // [undefined, undefined] move(); // [0, 0] 

上面代码是为函数move的参数指定默认值,而不是为变量xy指定默认值,因此会获得与前一种写法不一样的结果。

undefined就会触发函数参数的默认值。

[1, undefined, 3].map((x = 'yes') => x); // [ 1, 'yes', 3 ] [1, undefined, 3].map((x = 'yes') => x); // [ 1, 'yes', 3 ] 

6. 圆括号问题

解构赋值虽然很方便,可是解析起来并不容易。对于编译器来讲,一个式子究竟是模式,仍是表达式,没有办法从一开始就知道,必须解析到(或解析不到)等号才能知道。

由此带来的问题是,若是模式中出现圆括号怎么处理。ES6 的规则是,只要有可能致使解构的歧义,就不得使用圆括号。

可是,这条规则实际上不那么容易辨别,处理起来至关麻烦。所以,建议只要有可能,就不要在模式中放置圆括号。

不能使用圆括号的状况

如下三种解构赋值不得使用圆括号。

(1)变量声明语句

// 所有报错 let [(a)] = [1]; let {x: (c)} = {}; let ({x: c}) = {}; let {(x: c)} = {}; let {(x): c} = {}; let { o: ({ p: p }) } = { o: { p: 2 } }; // 所有报错 let [(a)] = [1]; let {x: (c)} = {}; let ({x: c}) = {}; let {(x: c)} = {}; let {(x): c} = {}; let { o: ({ p: p }) } = { o: { p: 2 } };

上面 6 个语句都会报错,由于它们都是变量声明语句,模式不能使用圆括号。

(2)函数参数

函数参数也属于变量声明,所以不能带有圆括号。

// 报错 function f([(z)]) { return z; } // 报错 function f([z,(x)]) { return x; } // 报错 function f([(z)]) { return z; } // 报错 function f([z,(x)]) { return x; }

(3)赋值语句的模式

// 所有报错 ({ p: a }) = { p: 42 }; ([a]) = [5]; // 所有报错 ({ p: a }) = { p: 42 }; ([a]) = [5];

上面代码将整个模式放在圆括号之中,致使报错。

// 报错 [({ p: a }), { x: c }] = [{}, {}]; // 报错 [({ p: a }), { x: c }] = [{}, {}];

上面代码将一部分模式放在圆括号之中,致使报错。

可使用圆括号的状况

可使用圆括号的状况只有一种:赋值语句的非模式部分,可使用圆括号。

[(b)] = [3]; // 正确 ({ p: (d) } = {}); // 正确 [(parseInt.prop)] = [3]; // 正确 [(b)] = [3]; // 正确 ({ p: (d) } = {}); // 正确 [(parseInt.prop)] = [3]; // 正确 

上面三行语句均可以正确执行,由于首先它们都是赋值语句,而不是声明语句;其次它们的圆括号都不属于模式的一部分。第一行语句中,模式是取数组的第一个成员,跟圆括号无关;第二行语句中,模式是p,而不是d;第三行语句与第一行语句的性质一致。

7. 用途

变量的解构赋值用途不少。

(1)交换变量的值

let x = 1; let y = 2; [x, y] = [y, x]; let x = 1; let y = 2; [x, y] = [y, x];

上面代码交换变量xy的值,这样的写法不只简洁,并且易读,语义很是清晰。

(2)从函数返回多个值

函数只能返回一个值,若是要返回多个值,只能将它们放在数组或对象里返回。有了解构赋值,取出这些值就很是方便。

// 返回一个数组  function example() { return [1, 2, 3]; } let [a, b, c] = example();  // 返回一个对象  function example() { return { foo: 1, bar: 2 }; } let { foo, bar } = example(); // 返回一个数组  function example() { return [1, 2, 3]; } let [a, b, c] = example();  // 返回一个对象  function example() { return { foo: 1, bar: 2 }; } let { foo, bar } = example();

(3)函数参数的定义

解构赋值能够方便地将一组参数与变量名对应起来。

// 参数是一组有次序的值 function f([x, y, z]) { ... } f([1, 2, 3]);  // 参数是一组无次序的值 function f({x, y, z}) { ... } f({z: 3, y: 2, x: 1}); // 参数是一组有次序的值 function f([x, y, z]) { ... } f([1, 2, 3]);  // 参数是一组无次序的值 function f({x, y, z}) { ... } f({z: 3, y: 2, x: 1});

(4)提取 JSON 数据

解构赋值对提取 JSON 对象中的数据,尤为有用。

let jsonData = { id: 42, status: "OK", data: [867, 5309] }; let { id, status, data: number } = jsonData; console.log(id, status, number); // 42, "OK", [867, 5309] let jsonData = { id: 42, status: "OK", data: [867, 5309] }; let { id, status, data: number } = jsonData; console.log(id, status, number); // 42, "OK", [867, 5309] 

上面代码能够快速提取 JSON 数据的值。

(5)函数参数的默认值

jQuery.ajax = function (url, { async = true, beforeSend = function () {}, cache = true, complete = function () {}, crossDomain = false, global = true,  // ... more config } = {}) {  // ... do stuff }; jQuery.ajax = function (url, { async = true, beforeSend = function () {}, cache = true, complete = function () {}, crossDomain = false, global = true,  // ... more config } = {}) {  // ... do stuff };

指定参数的默认值,就避免了在函数体内部再写var foo = config.foo || 'default foo';这样的语句。

(6)遍历 Map 结构

任何部署了 Iterator 接口的对象,均可以用for...of循环遍历。Map 结构原生支持 Iterator 接口,配合变量的解构赋值,获取键名和键值就很是方便。

const map = new Map(); map.set('first', 'hello'); map.set('second', 'world'); for (let [key, value] of map) { console.log(key + " is " + value); } // first is hello // second is world const map = new Map(); map.set('first', 'hello'); map.set('second', 'world'); for (let [key, value] of map) { console.log(key + " is " + value); } // first is hello // second is world 

若是只想获取键名,或者只想获取键值,能够写成下面这样。

// 获取键名 for (let [key] of map) {  // ... }  // 获取键值 for (let [,value] of map) {  // ... } // 获取键名 for (let [key] of map) {  // ... }  // 获取键值 for (let [,value] of map) {  // ... }

(7)输入模块的指定方法

加载模块时,每每须要指定输入哪些方法。解构赋值使得输入语句很是清晰。

const { SourceMapConsumer, SourceNode } = require("source-map"); const { SourceMapConsumer, SourceNode } = require("source-map");


原文地址:http://es6.ruanyifeng.com/#docs/destructuring

相关文章
相关标签/搜索