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

浏览器兼容性

另见