arguments 是 JavaScript 函數內部可用的特殊物件,雖然長得像陣列(有 length、索引存取),但它不是陣列(typeof arguments === 'object')。掌握它的特性與轉換技巧,能解鎖不定參數、函數柯里化、遞迴匿名函數等進階模式。
arguments.length:實際傳入參數個數arguments[i]:第 i 個參數(0-based)arguments.callee:指向正在執行的函數本身(嚴格模式禁用)arguments[i] 與對應命名參數雙向同步function format(template) {
var args = arguments; // 保存參數
var pattern = new RegExp("%([1-" + (arguments.length - 1) + "])", "g");
return String(template).replace(pattern, function(match, index) {
return args[index]; // %1 → args[1], %2 → args[2]...
});
}
format("And the %1 want to know whose %2 you %3", "papers", "shirt", "wear");
// "And the papers want to know whose shirt you wear"
// ES5 經典寫法
var args = Array.prototype.slice.call(arguments);
// ES6+ 簡潔寫法
const args = Array.from(arguments);
// 或
const args = [...arguments];
轉換後可使用 map、filter、reduce、push、pop 等陣列方法。
function makeFunc() {
var args = Array.from(arguments);
var fn = args.shift(); // 第一個參數是目標函數
return function() {
// 合併預設參數與呼叫時參數
return fn.apply(null, args.concat(Array.from(arguments)));
};
}
var majorTom = makeFunc(format, "This is Major Tom to ground control. I'm %1.");
majorTom("stepping through the door");
// "This is Major Tom to ground control. I'm stepping through the door."
arguments.callee)function repeat(fn, times, delay) {
return function() {
if (times-- > 0) {
fn.apply(null, arguments); // 執行原函數
var args = Array.from(arguments);
var self = arguments.callee; // 獲取自身引用
setTimeout(function() { self.apply(null, args); }, delay);
}
};
}
function comms(msg) { alert(msg); }
var somethingWrong = repeat(comms, 3, 2000);
somethingWrong("Can you hear me, major tom?");
// 彈窗 3 次,間隔 2 秒
⚠️ 注意:嚴格模式 ('use strict') 禁用 arguments.callee。現代寫法改用具名函數表達式:
const repeat = (fn, times, delay) => {
return function recur(...args) {
if (times-- > 0) {
fn(...args);
setTimeout(() => recur(...args), delay);
}
};
};
| 特性 | 非嚴格模式 | 嚴格模式 |
|---|---|---|
| arguments.callee | 可用 | ❌ TypeError |
| arguments 與參數同步 | 雙向同步 | 不同步 |
| arguments.caller | 非標準,部分支援 | ❌ 已移除 |
// ES6+ 推薦:完全替代 arguments
function format(template, ...values) {
return template.replace(/%(\d+)/g, (_, i) => values[i - 1] || '');
}
function repeat(fn, times, delay) {
return (...args) => {
if (times-- > 0) {
fn(...args);
setTimeout(() => repeat(fn, times, delay)(...args), delay);
}
};
}
arguments 是早期 JavaScript 實現不定參數、函數式編程的基石。雖然 ES6+ 的 ...rest、箭頭函數、具名函數表達式提供了更優雅的替代方案,但理解 arguments 的機制(類陣列、callee、參數同步)對於維護舊代碼、理解底層運作、面試應對仍極具價值。