萬盛學電腦網

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

JavaScript 內建 arguments 物件深度解析:從類陣列到函數式編程利器

arguments 是 JavaScript 函數內部可用的特殊物件,雖然長得像陣列(有 length、索引存取),但它不是陣列(typeof arguments === 'object')。掌握它的特性與轉換技巧,能解鎖不定參數、函數柯里化、遞迴匿名函數等進階模式。

核心特性

  • 所有函數(箭頭函數除外)自動擁有
  • 包含呼叫時傳入的所有實際參數
  • arguments.length:實際傳入參數個數
  • arguments[i]:第 i 個參數(0-based)
  • arguments.callee:指向正在執行的函數本身(嚴格模式禁用)
  • 非嚴格模式下,arguments[i] 與對應命名參數雙向同步

經典應用 1:不定參數函數(如格式化字串)

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"

經典應用 2:轉換為真正陣列

// ES5 經典寫法
var args = Array.prototype.slice.call(arguments);

// ES6+ 簡潔寫法
const args = Array.from(arguments);
// 或
const args = [...arguments];

轉換後可使用 map、filter、reduce、push、pop 等陣列方法。

經典應用 3:函數柯里化 / 部分應用

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."

經典應用 4:匿名函數遞迴(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、參數同步)對於維護舊代碼、理解底層運作、面試應對仍極具價值。

copyright © 萬盛學電腦網 all rights reserved