萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

JavaScript arguments 對象詳解:類數組、參數檢測、模擬重載

什麼是 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引用調用當前函數的函數(非標準,嚴格模式禁用)

常見應用場景

1. 參數個數檢測與預設值(ES6 默認參數前的寫法)

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

2. 模擬函數重載

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

3. 將 arguments 轉為真正陣列

// ES6
var args = Array.from(arguments);
// 或
var args = [...arguments];

// ES5
var args = Array.prototype.slice.call(arguments);
// 或
var args = [].slice.call(arguments);

4. 實現可變參數函數(如 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 與具名參數不再共享值,更安全、可優化。

箭頭函數無 arguments

var 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。
copyright © 萬盛學電腦網 all rights reserved