相信大家对数组里的length属性应该不陌生,它表示数组元素的个数,但是你有没有留意过,function里也有一个length属性
我们先来看一下它的定义
- length 是JS函数对象的一个属性值,该值是指 “该函数有多少个必须要传入的参数”,即形参的个数
- 形参的数量不包括剩余参数个数,仅包括 “第一个具有默认值之前的参数个数”
function a(x, y) {}
function b(x, y = 2, z) {}
function c(x, ...args) {}
console.log(a.length); //2
console.log(b.length); //1
console.log(c.length); //1
console.log((function(...args){}).length); // 0;
Function 构造器本身也是个Function。它的 length 属性值为 1 。该属性 Writable: false, Enumerable: false, Configurable: true。
console.log(Function.length); // 1
如果函数内部是通过arguments调用参数,而没有实际定义参数的话,length 只会的得到 0。
function test1() {
console.log(arguments.length);
}
console.log(test1.length); //0
test1(1, 2); // 2