File tree Expand file tree Collapse file tree 1 file changed +38
-1
lines changed Expand file tree Collapse file tree 1 file changed +38
-1
lines changed Original file line number Diff line number Diff line change @@ -86,11 +86,48 @@ fetch('http://example.com')
86
86
87
87
上面代码中,调用函数` fetch ` 时,第二个参数默认为一个空对象,而只要有第二个参数,` method ` 参数就默认为` GET ` 。
88
88
89
+ 请问下面两种写法有什么差别?
90
+
91
+ ``` javascript
92
+ // 写法一
93
+ function m1 ({x = 0 , y = 0 } = {}) {
94
+ return [x, y];
95
+ }
96
+
97
+ // 写法二
98
+ function m2 ({x, y} = { x: 0 , y: 0 }) {
99
+ return [x, y];
100
+ }
101
+ ```
102
+
103
+ 上面两种写法都对函数的参数设定了默认值,区别是写法一对` x ` 和` y ` 设定了默认值,写法二没有。
104
+
105
+ ``` javascript
106
+ // 函数没有参数的情况
107
+ m1 () // [0, 0]
108
+ m2 () // [0, 0]
109
+
110
+ // x和y都有值的情况
111
+ m1 ({x: 3 , y: 8 }) // [3, 8]
112
+ m2 ({x: 3 , y: 8 }) // [3, 8]
113
+
114
+ // x有值,y无值的情况
115
+ m1 ({x: 3 }) // [3, 0]
116
+ m2 ({x: 3 }) // [3, undefined]
117
+
118
+ // x和y都无值的情况
119
+ m1 ({}) // [0, 0];
120
+ m2 ({}) // [undefined, undefined]
121
+
122
+ m1 ({z: 3 }) // [0, 0]
123
+ m2 ({z: 3 }) // [undefined, undefined]
124
+ ```
125
+
89
126
通常情况下,定义了默认值的参数,都是函数的尾参数。因为这样比较容易看出来,到底省略了哪些参数。但是,非尾部的参数,也是可以设置默认值的。
90
127
91
128
``` javascript
92
129
// 例一
93
- function f (x = 1 , y ) {
130
+ function f (x = 1 , y ) {
94
131
return [x, y];
95
132
}
96
133
You can’t perform that action at this time.
0 commit comments