freeCodeCamp/guide/chinese/javascript/standard-objects/function/function-length/index.md

1.0 KiB
Raw Blame History

title localeTitle
Function Length 功能长度

功能长度

函数对象的length属性保存调用时函数所期望的参数数。

function noArgs() { } 
 
 function oneArg(a) { } 
 
 console.log(noArgs.length); // 0 
 
 console.log(oneArg.length); // 1 

ES2015语法

ES2015或通常称为ES6引入了rest操作符和默认函数参数。这两个添加都改变了length属性的工作方式。

如果在函数声明中使用了rest运算符或默认参数length属性将仅包含rest运算符或默认参数之前的参数数。

function withRest(...args) { } 
 
 function withArgsAndRest(a, b, ...args) { } 
 
 function withDefaults(a, b = 'I am the default') { } 
 
 console.log(withRest.length); // 0 
 
 console.log(withArgsAndRest.length); // 2 
 
 console.log(withDefaults.length); // 1 

有关Function.length更多信息可以在Mozilla的MDN Docs上找到。