length 属性指明函数的形参个数。
Function.length 属性的属性特性: |
|
|---|---|
| writable | false |
| enumerable | false |
| configurable | true |
描述
length 是函数对象的一个属性值,指该函数有多少个必须要传入的参数,即形参的个数。
形参的数量不包括剩余参数个数,仅包括第一个具有默认值之前的参数个数。
与之对比的是, arguments.length 是函数被调用时实际传参的个数。
Function 构造器的属性
Function 构造器本身也是个Function。他的 length 属性值为 1 。该属性 Writable: false, Enumerable: false, Configurable: true.
Function.prototype 对象的属性
Function.prototype 对象的 length 属性值为 0 。
示例
console.log(Function.length); /* 1 */
console.log((function() {}).length); /* 0 */
console.log((function(a) {}).length); /* 1 */
console.log((function(a, b) {}).length); /* 2 etc. */
console.log((function(...args) {}).length);
// 0, rest parameter is not counted
console.log((function(a, b = 1, c) {}).length);
// 1, only parameters before the first one with
// a default value is counted
规范
| Specification | Status | Comment |
|---|---|---|
| ECMAScript 1st Edition (ECMA-262) | Standard | Initial definition. Implemented in JavaScript 1.1. |
| ECMAScript 5.1 (ECMA-262) Function.length |
Standard | |
| ECMAScript 2015 (6th Edition, ECMA-262) Function.length |
Standard | The configurable attribute of this property is now true. |
| ECMAScript Latest Draft (ECMA-262) Function.length |
Draft |
浏览器兼容
Update compatibility data on GitHub
| Desktop | Mobile | Server | |||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
length |
Chrome Full support 1 | Edge Full support 12 | Firefox Full support 1 | IE Full support 4 | Opera Full support Yes | Safari Full support Yes | WebView Android Full support 1 | Chrome Android Full support 18 | Firefox Android Full support 4 | Opera Android Full support Yes | Safari iOS Full support Yes | Samsung Internet Android Full support 1.0 | nodejs Full support Yes |
| Configurable: true | Chrome Full support 43 | Edge Full support 12 | Firefox Full support 37 | IE No support No | Opera Full support 30 | Safari ? | WebView Android Full support 43 | Chrome Android Full support 43 | Firefox Android Full support 37 | Opera Android Full support 30 | Safari iOS ? | Samsung Internet Android Full support 4.0 | nodejs Full support Yes |
Legend
- Full support
- Full support
- No support
- No support
- Compatibility unknown
- Compatibility unknown