Skip to content

Commit c756397

Browse files
Merge pull request loverajoel#348 from neighborhood999/zh-TW
translate tip54
2 parents 0195f06 + 0b30ce1 commit c756397

File tree

1 file changed

+83
-0
lines changed

1 file changed

+83
-0
lines changed
Lines changed: 83 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,83 @@
1+
---
2+
layout: post
3+
4+
title: 如何使用在函式中的可選參數(包含 callback)
5+
tip-number: 54
6+
tip-username: alphashuro
7+
tip-username-profile: https://github.com/alphashuro
8+
tip-tldr: 你的 function 參數和 callback 是可選參數。
9+
10+
categories:
11+
- zh-TW
12+
---
13+
14+
Example function 中第二個和第三個為可選的參數:
15+
16+
```javascript
17+
function example( err, optionalA, optionalB, callback ) {
18+
// 以陣列形式取得參數。
19+
var args = new Array(arguments.length);
20+
for(var i = 0; i < args.length; ++i) {
21+
args[i] = arguments[i];
22+
};
23+
24+
// 第一個參數是一個 error 物件,
25+
// 從陣列移除第一個參數,並將它回傳。
26+
err = args.shift();
27+
28+
// 如果最後一個參數是 function,那它則為 callback function。
29+
// 移除在陣列中最後一個參數,並將它回傳。
30+
if (typeof args[args.length-1] === 'function') {
31+
callback = args.pop();
32+
}
33+
34+
// 如果還有其他參數,
35+
// 那些都是可選參數,你可以像這樣一個一個將他取出:
36+
if (args.length > 0) optionalA = args.shift(); else optionalA = null;
37+
if (args.length > 0) optionalB = args.shift(); else optionalB = null;
38+
39+
// 像往常一樣︰檢查是否有錯誤。
40+
if (err) {
41+
return callback && callback(err);
42+
}
43+
44+
// 為了這個教學,log 是可選的參數。
45+
console.log('optionalA:', optionalA);
46+
console.log('optionalB:', optionalB);
47+
console.log('callback:', callback);
48+
49+
/* 你任何想做的邏輯。 */
50+
51+
}
52+
53+
// ES6 程式碼更簡短、更簡潔。
54+
function example(...args) {
55+
// 第一個參數是一個 error 物件
56+
const err = args.shift();
57+
// 如果最後一個參數是 function,那它則為 callback function。
58+
const callback = (typeof args[args.length-1] === 'function') ? args.pop() : null;
59+
60+
// 如果還有其他參數,那些都是可選參數,你可以像這樣一個一個將他取出:
61+
const optionalA = (args.length > 0) ? args.shift() : null;
62+
const optionalB = (args.length > 0) ? args.shift() : null;
63+
// ... repeat for more items
64+
65+
if (err && callback) return callback(err);
66+
67+
/* 你任何想做的邏輯。 */
68+
}
69+
70+
// 調用 example function 和沒有可選的參數。
71+
72+
example(null, 'AA');
73+
74+
example(null, function (err) { /* 你任何想做的邏輯。 */ });
75+
76+
example(null, 'AA', function (err) {});
77+
78+
example(null, 'AAAA', 'BBBB', function (err) {});
79+
```
80+
81+
### 我要如何確認 optionalA 或 optionalB 是預期的?
82+
83+
設計你的 function,為了接受 optionalB 而要求 optionalA。

0 commit comments

Comments
 (0)