函數的length
屬性指明函數的形參個數。
length
是函數對象的一個屬性值,指該函數有多少個必須要傳入的參數,即形參的個數。形參的數量不包括剩余參數個數,僅包括第一個具有默認值之前的參數個數。與之對比的是, arguments.length
是函數被調用時實際傳參的個數。
Function
構造器本身也是個Function。它的 length
屬性值為 1 。該屬性 Writable: false
, Enumerable: false
, Configurable: true。
1. Function構造器的屬性的length為1
console.log(Function.length); // 1
console.log(function(a){}.length); // 1
console.log(function(a,b,c){}.length); // 3
2.如果函數內部是通過arguments調用參數,而沒有實際定義參數的話,length 只會的得到 0。
function test1(){ console.log(arguments.length); } console.log(test1.length); //0 test1(1,2);// 2
ES6指定了默認值以后,函數的length屬性,將返回沒有指定默認值的參數個數。也就是說,指定了默認值后,length屬性將失真。下面代碼中,length屬性的返回值,等於函數的參數個數減去指定了默認值的參數個數。
這時因為length屬性的含義是,該函數預期傳入的參數個數。某個參數指定默認值以后,預期傳入的參數個數就不包括這個參數了。
console.log((function (a){}).length); // 1 console.log((function (a = 5){}).length); // 0 console.log((function(a, b, c = 5){}).length); // 2; /* 同時,這里的rest參數也不會計入length屬性。*/ console.log((function(...args){}).length); // 0; /*如果設置了默認值的參數不是尾參數,那么length屬性也不再計入后面的參數了*/ (function(a = 0, b, c){}).length; // 0 (function(a, b = 1, c){}).length; // 1
function a(a,{...b}){
console.log('執行吧')
}
console.log(a)//2
function a(a,...b){
console.log('執行吧')
}
console.log(a)//1