Function: length

Baseline 已廣泛支援

此特性已相當成熟,可在許多裝置和瀏覽器版本上使用。自 ⁨2015 年 7 月⁩以來,各瀏覽器均已提供此特性。

length 資料屬性是 Function 例項的一個屬性,用於指示該函式期望的引數數量。

試一試

function func1() {}

function func2(a, b) {}

console.log(func1.length);
// Expected output: 0

console.log(func2.length);
// Expected output: 2

一個數字。

Function: length 屬性的屬性特性
可寫
可列舉
可配置

描述

Function 物件的 length 屬性表示該函式期望的引數數量,即形參的數量。

  • 只有在第一個具有 預設值 的引數之前的引數才會被計數。
  • 解構賦值 模式被視為一個引數。
  • 剩餘引數(rest parameter)被排除在外。

相比之下,arguments.length 是函式區域性的,表示實際傳遞給函式的引數數量。

Function 建構函式本身就是一個 Function 物件。它的 length 資料屬性值為 1

出於歷史原因,Function.prototype 本身也是可呼叫的。Function.prototypelength 屬性值為 0

示例

使用函式 length

js
console.log(Function.length); // 1

console.log((() => {}).length); // 0
console.log(((a) => {}).length); // 1
console.log(((a, b) => {}).length); // 2 etc.

console.log(((...args) => {}).length);
// 0, rest parameter is not counted

console.log(((a, b = 1, c) => {}).length);
// 1, only parameters before the first one with
// a default value are counted

console.log((({ a, b }, [c, d]) => {}).length);
// 2, destructuring patterns each count as
// a single parameter

規範

規範
ECMAScript® 2026 語言規範
# sec-function-instances-length

瀏覽器相容性

另見