一.数组的解构赋值
1.举几个例子足以理解
let [a, b, c] = [1, 2, 3]; a:1; b:2; c:3;
let [x, , y] = [1, 2, 3]; x:1 y:2;
let [foo, [[bar], baz]] = [1, [[2], 3]]; foo:1; bar:2; baz:3;
let [head, ...tail] = [1, 2, 3, 4];head:1; tail:[2,3,4];
- let [a, [b], d] = [1, [2, 3], 4];a:1 b:2 d:4;
二.对象的解构赋值
1.举几个例子足以理解
let { a, b} = { a: "aaa", b: "bbb" };a:"aaa" b:"bbb";
let { c } = { a: "aaa", b: "bbb" };c:
undefined;
let obj = { p: [ 'Hello', { y: 'World' } ] }; let { p: [x, { y }] } = obj;x:'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}
var { message: msg = 'Something went wrong' } = {}; msg // "Something went wrong"(对象的解构赋值也可以设置默认值);默认值生效的条件:对象的属性值严格等于
undefined
。var {x = 3} = {x: null}; x // null;null 不严格的等于undefined;
// 报错 let {foo: {bar}} = {baz: 'baz'}; foo的值等于undefined;undefined没有bar属性;
// 错误的写法 let x; {x} = {x: 1}; // SyntaxError: syntax error;对于已经声明的值进行解构赋值的时候要格外小心;正确写法({x} = {x: 1});不加小括号的时候,{x}是一个独立的代码块;
常用的场景:let { log, sin, cos } = Math;
let arr = [1, 2, 3]; let {0 : first, [arr.length - 1] : last} = arr; first // 1 last // 3
三.字符串的解构赋值
1.仍然举几个例子说事情:
const [a, b, c, d, e] = 'hello'; a // "h" b // "e" c // "l" d // "l" e // "o";
let {length : len} = 'hello'; len // 5; 因为'hello'也有length属性,所以,len==5;
四.数值和布尔值的解构赋值
1.解构赋值时,如果等号右边是数值和布尔值,则会先转为对象。
let {toString: s} = 123; s === Number.prototype.toString // true let {toString: s} = true; s === Boolean.prototype.toString // true;;;;上面代码中,数值和布尔值的包装对象都有
toString
属性,因此变量s
都能取到值。let { prop: x } = undefined; // TypeError let { prop: y } = null; // TypeError;;;解构赋值的规则是,只要等号右边的值不是对象或数组,就先将其转为对象。由于
undefined
和null
无法转为对象,所以对它们进行解构赋值,都会报错。
五.函数参数的解构赋值
1.function add([x, y]){ return x + y; } add([1, 2]); // 3
2.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];带有默认值的函数;
五.函数参数的解构赋值
1.圆括号的问题:ES6 的规则是,只要有可能导致解构的歧义,就不得使用圆括号。下列情况均会报错:
- 变量的声明不可以使用圆括号;
- 函数参数不允许使用圆括号;
- 复制语句模式不可以使用圆括号;
ES6的文档下面还有部分内容,如果感兴趣可以自己再去浏览:变量的解构赋值;