From 2d74dbcde9efb01810cf4cf64c8a116ab39ef96d Mon Sep 17 00:00:00 2001 From: Ruan Yifeng Date: Sat, 14 Mar 2015 17:51:30 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BF=AE=E6=94=B9destructuring?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/destructuring.md | 39 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) diff --git a/docs/destructuring.md b/docs/destructuring.md index 5388355..267da18 100644 --- a/docs/destructuring.md +++ b/docs/destructuring.md @@ -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