ES6 引入默認參數語法前,開發者需手動在函數內部實現默認值邏輯。本文回顧三種經典模式,並對比現代標準寫法。
arguments + 三元運算符function test(a, b) {
var a = arguments[0] !== undefined ? arguments[0] : 1;
var b = arguments[1] !== undefined ? arguments[1] : 9;
return a + b;
}
console.log(test()); // 10
console.log(test(5)); // 14
console.log(test(5, 6)); // 11
console.log(test(null, 6)); // 16 (null !== undefined,不觸發默認值)
console.log(test(undefined, 6)); // 7 (觸發默認值)
注意:arguments[0] ? arguments[0] : 1 會誤判 0、''、false 為「未傳遞」,應用 !== undefined 判斷。
|| 運算符function test(blog, address) {
blog = blog || '默認博客名';
address = address || 'https://default.com';
console.log(blog, address);
}
test(); // 默認博客名 https://default.com
test('csdn', 'blog.csdn.net'); // csdn blog.csdn.net
test('', 'custom.com'); // 默認博客名 custom.com ← 空字串被視為 falsy,觸發默認值
缺點:無法傳遞 0、''、false、null 等 falsy 值作為有效參數。
$.extend / Object.assign(參數較多時推薦)function test(options) {
var defaults = {
name: '程序愛好者',
age: 18,
phone: '15600000000',
qq: '123456',
message: '歡迎加入'
};
// 淺合併:用戶傳入的覆蓋默認值
var settings = $.extend({}, defaults, options); // 或 Object.assign({}, defaults, options)
console.log('姓名:' + settings.name);
console.log('年齡:' + settings.age);
// ...
}
test(); // 全部默認值
test({ name: 'dwqs', age: 20, qq: '461147874', message: '博客:www.example.com' });
// 輸出:姓名:dwqs,年齡:20,電話:15600000000 (保留默認),QQ:461147874,說明:博客:www.example.com
優點:參數順序無關、可選參數多、語義清晰、易擴展。
function test(a = 1, b = 9) {
return a + b;
}
console.log(test()); // 10
console.log(test(5)); // 14
console.log(test(5, 6)); // 11
console.log(test(null, 6)); // null + 6 = 6 (null 不觸發默認值)
console.log(test(undefined, 6)); // 1 + 6 = 7 (undefined 觸發默認值)
// 1. 默認值可為表達式/函數調用
function fetchData(url, timeout = 3000, headers = getDefaultHeaders()) { ... }
// 2. 後參數引用前參數
function createUser(name, id = generateId(name)) { ... }
// 3. 解構賦值結合默認值
function connect({ host = 'localhost', port = 3306, user = 'root' } = {}) { ... }
connect(); // 全部默認
connect({ port: 5432 }); // 僅覆蓋 port
| 模式 | 適用場景 | 優點 | 缺點 |
|---|---|---|---|
| arguments + !== undefined | 早期兼容、需區分 undefined/null | 精確控制 | 代碼冗長、易寫錯 |
| 邏輯或 || | 簡單場景、確定不傳 falsy 值 | 極其簡潔 | 誤判 falsy 值 |
| 配置物件 + extend/assign | 參數多、可選項多、需深度合併 | 語義清晰、擴展性強 | 需引入庫或 ES6 |
| ES6 默認參數 | 現代項目 (Babel/TypeScript/Node 6+) | 標準、語法級支持、無誤判、支持解構 | 舊環境需轉譯 |
arguments 和 || 技巧,除非維護無法轉譯的舊代碼。@param {Type} [name=default] 描述 標註默認值。