length
属性返回在 函数 中列出的形式参数的数量。
示例
// function definition
function func1(a, b) {
}
// finding the number of parameters inside func1
console.log(func1.length);
// Output: 2
length 语法
length
属性的语法是
func.length
其中,func
是一个函数。
length 参数
length
属性不接受任何参数。
length 返回值
length
属性返回给定函数的形参数量。
示例 1:使用 length 属性
// function definition
function func() {}
// finding number of parameters inside func()
console.log(func.length);
// function definition
function func1(a, b) {}
// finding the number of parameters inside func1()
console.log(func1.length);
输出
0 2
在上面的程序中,我们使用了 length 属性来查找 func()
和 func1()
中的参数数量。
func()
没有参数,所以 func.length
返回 0。func1
中有两个参数 a
和 b
,所以 func1.length
返回 2。
示例 2:length 属性与参数数组
当函数中列出了参数数组时,length
属性返回 0。例如
// defining a function with an array of arguments
function func2(...args) {
}
// finding number of parameters inside func2()
console.log(func2.length);
输出
0
在上面的示例中,在 func2()
中列出了一个参数数组。所以 func2.length
返回 0。
示例 3:length 属性与默认参数值
length
属性会跳过剩余参数,并且只计算到第一个具有默认值的参数。例如
// defining a function with default parameter
function func3(a, b = 10, c) {
}
// only parameters before the one with
// default value are counted
console.log(func3.length);
输出
1
在上面的程序中,func3.length
跳过了具有默认值的 b
以及默认值之后的 c
。因此,该方法返回 1。
另请阅读