此页面由社区从英文翻译而来。了解更多并加入 MDN Web Docs 社区。
Function:length
Baseline Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since 2015年7月.
Function 实例的length 数据属性表示函数期望的参数数量。
In this article
尝试一下
function func1() {}function func2(a, b) {}console.log(func1.length);// Expected output: 0console.log(func2.length);// Expected output: 2值
一个数字。
Function:length 的属性特性 | |
|---|---|
| 可写 | 否 |
| 可枚举 | 否 |
| 可配置 | 是 |
描述
一个Function 对象的length 属性表示函数期望的参数个数,即形参的个数。这个数字不包括剩余参数,只包括在第一个具有默认值的参数之前的参数。相比之下,arguments.length 是局限于函数内部的,它提供了实际传递给函数的参数个数。
Function 构造函数本身就是一个Function 对象。它的length 数据属性的值为1。
由于历史原因,Function.prototype 本身是可调用的。Function.prototype 的length 属性的值为0。
示例
>使用 function length
js
console.log(Function.length); // 1console.log((() => {}).length); // 0console.log(((a) => {}).length); // 1console.log(((a, b) => {}).length); // 2,依此类推console.log(((...args) => {}).length);// 0,剩余参数不计算在内console.log(((a, b = 1, c) => {}).length);// 1,只计算第一个具有默认值的参数之前的参数规范
| Specification |
|---|
| ECMAScript® 2026 Language Specification> # sec-function-instances-length> |