1
0
mirror of https://github.com/ruanyf/es6tutorial.git synced 2025-05-24 18:32:22 +00:00

修改destructuring

This commit is contained in:
Ruan Yifeng 2015-03-14 17:51:30 +08:00
parent ddc4cd5d63
commit 2d74dbcde9

View File

@ -144,6 +144,11 @@ baz // undefined
var { foo: baz } = { foo: "aaa", bar: "bbb" };
baz // "aaa"
let obj = { first: 'hello', last: 'world' };
let { first: f, last: l } = obj;
f // 'hello'
l // 'world'
```
和数组一样,解构也可以用于嵌套结构的对象。
@ -175,6 +180,40 @@ console.log(x, y) // 1, 5
```
对象解构可以与函数参数的默认值一起使用。
```javascript
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的参数是一个对象通过对这个对象进行解构得到变量x和y的值。如果解构失败x和y等于默认值。
注意,指定函数参数的默认值时,不能采用下面的写法。
```javascript
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的参数指定默认值而不是为变量x和y指定默认值所以会得到与前一种写法不同的结果。
如果要将一个已经声明的变量用于解构赋值,必须非常小心。
```javascript