js获取函数定义的参数个数

  js如何获取函数function定义的参数个数,可以调用方法的length属性获取显示定义的形参个数。

Function.length

概述

length 属性指明函数的形参个数。

Function.length 属性的属性特性:
writable false
enumerable false
configurable true

描述

length 是函数对象的一个属性值,指明该函数期望多少个参数,意即形参的个数。数量不包括剩余参数。相比之下,  arguments.length 是函数被调用时实际传参的个数。

Function 构造器的属性

Function 构造器本身也是个Function。他的 length 属性值为 1 。该属性 Writable: false, Enumerable: false, Configurable: true.

Function 原型对象的属性

Function 原型对象的 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 */
 
如果函数内部是通过 arguments 调用参数,而没有实际定义参数的话,length 只会的得到 0

规范

Specification Status Comment
ECMAScript 1st Edition. Standard Initial definition. Implemented in JavaScript 1.1.
length property of the Function constructor:
ECMAScript 5.1 (ECMA-262)
Function.length

length property of the Function prototype object:
ECMAScript 5.1 (ECMA-262)
Function.length

length property of Function instances:
ECMAScript 5.1 (ECMA-262)
Function.length
Standard  
length property of the Function constructor:
ECMAScript 6 (ECMA-262)
Function.length

length property of the Function prototype object:
ECMAScript 6 (ECMA-262)
Function.length

length property of Function instances:
ECMAScript 6 (ECMA-262)
Function.length
Release Candidate The configurable attribute of this property is now true.

浏览器兼容性

Desktop
Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari
Basic support (Yes) (Yes) (Yes) (Yes) (Yes)
Configurable: true ? 37 (37) ? ? ?

Mobile

Feature Android Chrome for Android Firefox Mobile (Gecko) IE Mobile Opera Mobile Safari Mobile
Basic support (Yes) (Yes) (Yes) (Yes) (Yes) (Yes)
Configurable: true ? ? 37.0 (37) ? ? ?

来源:https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Function/length

加支付宝好友偷能量挖...


评论(0)网络
阅读(390)喜欢(0)JavaScript/Ajax开发技巧