JavaScript 終於讓函數也能有預設值了,在 ES6 中為函數加入了預設參數 (Default parameters) 與 Rest 參數的語法,在設計或建構時能更直覺的加入參數值了。
函數中的預設參數
主要用途
預設參數是為了代替傳統的方式,解決了需要判斷是否為undefined
才能設置預設值的麻煩
1 2 3 4 5 6 7 8 9 10 11 12
| function multiply(a, b = 1) { return console.log(a * b); }
function multiply(a, b) { b = (typeof b !== 'undefined') ? b : 1; return console.log(a * b); }
multiply(10, 2); multiply(10);
|
使用特性
- 預設參數可以是任何表達式,甚至可以取前一個變數來使用
1 2 3 4 5 6
| function defaultParam(){ return 'test'; } function foo(a, b = a * 2, c = defaultParam()) { console.log(a, b, c); }
foo(10);
|
1 2 3 4 5 6 7 8 9 10 11 12
|
function foo({x = 0, y = 0} = {}) { return console.log([x, y]); }
foo(); foo({}); foo({x: 10, y: 20}); foo({x: 5}); foo({z: 1});
|
- 如果傳入
undefined
將會觸發參數等於預設值,但傳入null
則沒有這個效果
1 2 3 4 5 6
| function foo(x = 5, y = 10) { console.log(x, y); }
foo(undefined, null);
|
Rest 參數
主要用途
- Rest 參數是取得剩下的參數後存放在同一個陣列裡
- 由三個點組成
...
,後面再加上陣列變數名稱,與擴展運算子很相似,但兩者是相反的概念
- 主要是代替函數中的
arguments
物件,其實不能說完全取代,因為arguments
內還有其他參數,但常用來獲取裡面的陣列,只是繁瑣的轉換過程比較麻煩
1 2 3 4 5 6 7 8 9 10 11
| function foo(...rest) { return console.log(rest); }
function foo() { return console.log(Array.prototype.slice.call(arguments)); }
foo(); foo(10, 20, 30);
|
使用特性
1 2
| function foo(a, ...b, c) {}
|
- 主要是放在函數中使用,但也能拿來做解構賦值
- 在進行解構賦值時,等號左邊可以使用 rest 參數,右邊使用為 spread 擴展運算子
1 2 3 4 5 6 7 8 9
|
let spread1 = [5, 2, 8]; let spread2 = [6, 1, 3];
let [first, ...rest] = [...spread1, ...spread2].sort();
console.log(first); console.log(rest);
|