arguments?arguments 是函數內部自動可用的類陣列對象,包含調用函數時傳入的所有實參。它不是陣列,但有 length 屬性且可用索引訪問。
function sayHi() {
console.log(arguments[0]); // 第一個參數
console.log(arguments.length); // 參數個數
}
sayHi('Hello', 'World'); // Hello, 2
| 特性 | 說明 |
|---|---|
| 類陣列 | 有 length、索引訪問,但無 push/pop/map 等陣列方法 |
| 非嚴格模式下映射 | 修改 arguments[i] 會同步修改對應具名參數,反之亦然(嚴格模式下斷開映射) |
callee | 引用當前執行的函數(嚴格模式禁用,避免使用) |
caller | 引用調用當前函數的函數(非標準,嚴格模式禁用) |
function multiply(a, b) {
b = (typeof b !== 'undefined') ? b : 1; // 或 b = b || 1 (但 0 會被誤判)
return a * b;
}
console.log(multiply(5)); // 5
console.log(multiply(5, 2)); // 10
function doAdd() {
if (arguments.length === 1) {
return arguments[0] + 5;
} else if (arguments.length === 2) {
return arguments[0] + arguments[1];
} else {
throw new Error('參數個數錯誤');
}
}
console.log(doAdd(10)); // 15
console.log(doAdd(10, 20)); // 30
arguments 轉為真正陣列// ES6
var args = Array.from(arguments);
// 或
var args = [...arguments];
// ES5
var args = Array.prototype.slice.call(arguments);
// 或
var args = [].slice.call(arguments);
console.log 風格)function log(prefix) {
var args = Array.prototype.slice.call(arguments, 1);
console.log.apply(console, [prefix].concat(args));
}
log('[INFO]', 'User', 'login', { id: 1 });
'use strict';
function test(a) {
a = 10;
console.log(arguments[0]); // 仍為原始傳入值,不再同步
}
test(5); // 輸出 5
嚴格模式下 arguments 與具名參數不再共享值,更安全、可優化。
argumentsvar arrow = () => { console.log(arguments); }; // ReferenceError: arguments is not defined
// 解決:使用剩餘參數
var arrow = (...args) => { console.log(args); }; // 真正的陣列
arguments 會阻礙 JIT 優化(V8 等引擎)。...args(ES6),獲得真正陣列且效能更優。arguments 是函數內部的類陣列,包含所有實參。callee/caller。...rest 參數,完全替代 arguments。