解构赋值(destructuring assignment)语法是一个Javascript表达式,这种语法可以更方便的提取出 Object 或者 Array 中的数据。这种语法能够在接受提取的数据的地方使用,好比一个表达式的左边。有明确的语法模式来告诉咱们如何使用这种语法提取须要的数据值。html
解构 Object:es6
const obj = { first: 'Jane', last: 'Doe' }; const {first: f, last: l} = obj; // f = 'Jane'; l = 'Doe' // {prop} is short for {prop: prop} const {first, last} = obj; // first = 'Jane'; last = 'Doe'
解构能帮助更好地处理方法返回的对象:数组
const obj = { foo: 123 }; const {writable, configurable} = Object.getOwnPropertyDescriptor(obj, 'foo'); console.log(writable, configurable); // true true
解构数组,对全部可遍历的值有效。bash
let foo = ["one", "two", "three"]; let [one, two, three] = foo; console.log(one); // "one" console.log(two); // "two" console.log(three); // "three" const iterable = ['a', 'b']; const [x, y] = iterable; // x = 'a'; y = 'b' [x, y] = iterable; // window.x = 'a'; window.y = 'b';
一样的,解构数组也能帮助咱们更好地处理函数返回值:app
const [all, year, month, day] = /^(\d\d\d\d)-(\d\d)-(\d\d)$/ .exec('2999-12-31');
并且,你也能够忽略你不感兴趣的返回值:函数
function f() { return [1, 2, 3]; } let [a, , b] = f(); console.log(a); // 1 console.log(b); // 3
你也能够忽略所有返回值,不过彷佛没啥用:ui
[,,] = f();
当解构一个数组时,可使用剩余模式(拓展语句,Spread operator),将数组剩余部分赋值给一个变量。prototype
let [a, ...b] = [1, 2, 3]; console.log(a); // 1 console.log(b); // [2, 3]
解构能够在下面这些情景中使用,只展示了数组模式的演示,对象模式也是如此。rest
// 变量声明: const [x] = ['a']; let [x] = ['a']; var [x] = ['a']; // 赋值: 下面这种状况将会在全局变量上添加一个 x 属性,值为‘a‘ [x] = ['a']; // 参数的定义: function userId({id}) { return id; } function whois({displayName: displayName, fullName: {firstName: name}}){ console.log(displayName + " is " + name); } var user = { id: 42, displayName: "jdoe", fullName: { firstName: "John", lastName: "Doe" } }; console.log("userId: " + userId(user)); // "userId: 42" whois(user); // "jdoe is John" function f([x]) { ··· } f(['a']);
也能够在 for-of 循环中使用:code
const arr = ['a', 'b']; for (const [index, element] of arr.entries()) { console.log(index, element); } // Output: // 0 a // 1 b
在解构中,有下面两部分参与:
Destructuring source: 解构的源,将要被解构的数据,好比解构赋值表达式的右边部分。
Destructuring target: 解构的目标,好比解构复制表达式的左边部分。
解构的目标能够是下面三个的任意一个:
赋值对象,Assigment Patterns。例如 x
赋值对象一般来讲是一个变量。可是在解构赋值中,你有更多的选择,稍后会讲到。
对象模型,Object Patterns。好比:{ first: «pattern», last: «pattern» }
数组模型,Object Patterns。好比:[ «pattern», «pattern» ]
能够任意嵌套模型,并且是能够很是任性的嵌套。
const obj = { a: [{ foo: 123, bar: 'abc' }, {}], b: true }; const { a: [{foo: f}] } = obj; // f = 123
在一个表达式pattern = someValue
中,pattern
是如何访问someValue
的呢?
在访问属性以前,object pattern 将解构的源数据(destructuing source)转换成对象。
const {length : len} = 'abc'; // len = 3 const {toString: s} = 123; // s = Number.prototype.toString
在这个过程当中,强制转换成对象的过程不是经过Object()
方法,而是经过内置的操做方法toObject()。这两个操做处理undefined
和null
的方式不太同样。
Object()方法将原始类型值转换成包装类型对象(wrapper object),原来的值原封不动。
> typeof Object('abc') 'object' > var obj = {}; > Object(obj) === obj true
也会将undefined
和 null
转换成一个空的对象。
> Object(undefined) {} > Object(null) {}
对比之下,当遇到undefined
和null
的时候,toObject()方法则会抛出一个错误。因此下面的解构是失败的:
const { prop: x } = undefined; // TypeError const { prop: y } = null; // TypeError
所以,你可使用空对象模型{}来检查一个值是否被强制转换成了一个对象。正如前面提到的规则,undefined
和null
将会抛出错误
({} = [true, false]); // OK, Arrays are coercible to objects ({} = 'abc'); // OK, strings are coercible to objects ({} = undefined); // TypeError ({} = null); // TypeError
表达式两边的括号是必须的,由于在 JavaScript 中,声明不能以花括号开始。
数组解构使用一个迭代器来获取数据源中的元素。所以,你能够对任何能够遍历的值使用数组解构。
字符串是可遍历的:
const [x, ...y] = 'abc'; // x='a'; y=['b', 'c']
咱们没法经过索引访问 Set中的元素,可是能够经过迭代器。因此,数组解构可以在 Sets上工做:
const [x,y] = new Set(['a', 'b']); // x='a'; y='b’;
Set
的迭代器老是按照元素插入的顺序将元素返回,因此上述的解构返回的结果老是相同的。
若是一个值有一个 key 为Symbol.iterator
的方法,这个方法返回的是一个对象,那么这个值是能够遍历的。若是被解构的值不能遍历的,那么“数组解构”会抛出一个TypeError
错误。
let x; [x] = [true, false]; // OK, Arrays are iterable [x] = 'abc'; // OK, strings are iterable [x] = { * [Symbol.iterator]() { yield 1 } }; // OK, iterable [x] = {}; // TypeError, empty objects are not iterable [x] = undefined; // TypeError, not iterable [x] = null; // TypeError, not iterable
能够用一个空的数组模型[]来检查值是否是可遍历的:
[] = {}; // TypeError, empty objects are not iterable [] = undefined; // TypeError, not iterable [] = null; // TypeError, not iterable
默认值是可选的,在数据源中找不到对应的值时,若是设置了默认值,则匹配这个默认值做为匹配结果,不然返回 undefined。
const [x=3, y] = []; // x = 3; y = undefined。 const {foo: x=3, bar: y} = {}; // x = 3; y = undefined
当解构模式有匹配结果,且匹配结果是 undefined 时,也会使用默认值做为返回结果:
const [x=1] = [undefined]; // x = 1 const {prop: y=2} = {prop: undefined}; // y = 2
也就是说下面的解构:
const {prop: y=someFunc()} = someValue;
至关于:
let y; if (someValue.prop === undefined) { y = someFunc(); } else { y = someValue.prop; }
使用console.log()
能够观察到:
> function log(x) { console.log(x); return 'YES' } > const [a=log('hello')] = []; > a 'YES' > const [b=log('hello')] = [123]; > b 123
在第二个解构中,默认值没有触发,而且log()
没有被调用。
默认值能够引用模式中的任何变量,包括相同模式中的其余变量:
const [x=3, y=x] = []; // x=3; y=3 const [x=3, y=x] = [7]; // x=7; y=7 const [x=3, y=x] = [7, 2]; // x=7; y=2
可是,变量的顺序很关键,从左到右,先声明的变量不能引用后声明的变量,也就是左边的不能引用右边的。
const [x=y, y=3] = []; // ReferenceError
到目前为止,咱们所看到的都是模式中变量的默认值,咱们也能够为模式设置默认值。
const [{prop: x} = {}] = [];
若是整个模式没有匹配结果,则使用{}
做为数据源来匹配。
const { prop: x } = {}; // x = undefined
上面的例子中,x 为 undefined 可能仍是不够直观。看下面这个例子:
const [{prop: x} = {props: 'abc'}] = []; // x=abc
若是属性值是一个变量,和属性的 key相同,就能够忽略这个 key:
const { x, y } = { x: 11, y: 8 }; // x = 11; y = 8 // 等价于 const { x: x, y: y } = { x: 11, y: 8 };
若是把表达式放入方括号中,能够用这个表达式声明属性的键:
const FOO = 'foo'; const { [FOO]: f} = {fooL 123}; // f = 123
这也使得可使用 symbols 来作属性的键:
// Create and destructure a property whose key is a symbol const KEY = Symbol(); const obj = { [KEY]: 'abc' }; const { [KEY]: x } = obj; // x = 'abc' // Extract Array.prototype[Symbol.iterator] const { [Symbol.iterator]: func } = []; console.log(typeof func); // function
在解构的过程当中能够跳过一些元素:
const [,,x,y] = [1,2,3,4]; // x= 3 y = 4;
剩余运算符能够将一个可遍历对象中剩余的元素提取到一个数组中。若是这个运算符在数组模式中使用,运算符必须放在最后:
const [x, ...y] = [1,2,3,4]; // x=1; y=[2,3,4];
要注意的时,拓展运算符(spread operator)与剩余操做符有着相同的语法-三个点。可是它们之间有区别:前者将数组变成多个元素;后者则用来解构和提取数据,多个元素压缩成一个元素。
若是运算符找不到任何元素,将会匹配一个空的数组,永远不会返回undefined 或者 null。例如:
const [x, y, ...z] = ['a']; // x='a'; y=undefined; z
操做符不必定非要是一个变量,也可使用模式:
const [x, ...[y, z]] = ['a', 'b', 'c']; // x = 'a'; y = 'b'; z = 'c'
在使用解构的时候,有两点要考虑清楚:
不能使用大括号做为声明语句的开头;
在解构的过程当中,能够申明变量或者分配给变量,可是不能同时这么作;
在 for-of 中使用解构:
const map = new Map().set(false, 'no').set(true, 'yes'); for (const [key, value] of map) { console.log(key + ' is ' + value); }
使用解构交换两个变量的值:
[a, b] = [b, a];
或者:
[a, b, c] = [c, a, b];
还能够分割数据:
const [first, ...rest] = ['a', 'b', 'c']; // first = 'a'; rest = ['b', 'c']
处理方法返回的数组更加方便:
const [all, year, month, day] = /^(\d\d\d\d)-(\d\d)-(\d\d)$/.exec('2999-12-31'); const cells = 'Jane\tDoe\tCTO' const [firstName, lastName, title] = cells.split('\t'); console.log(firstName, lastName, title);
要注意的一点是:exec等一些方法可能会返回 null,致使程序抛出错误TypeError
,此时须要添加一个默认值:
const [, year, month, day] = /^(\d\d\d\d)-(\d\d)-(\d\d)$/.exec(someStr) || [];
参考资料: