1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 ????<meta charset="UTF-8"> 5 ????<title>length 属性</title> 6 </head> 7 <body> 8 <script> 9 ??// length 是函数对象的一个属性值,指该函数有多少个必须要传入的参数,即形参的个数10 ??// 形参的数量不包括剩余参数个数,仅包括第一个具有默认值之前的参数个数11 ??// 如下:12 13 ??// 0, rest parameter is not counted 不包括剩余参数个数14 ??console.log("function(...args)",(function(...args) {}).length); // 015 16 ??//有默认值:包括第一个具有默认值之前的参数个数17 ??console.log("function()",function(){}.length); // 018 ??console.log("function(a = 1, b, c)",(function(a = 1, b, c) {}).length); // 019 ??console.log("function(a, b = 1, c)",(function(b, a = 1, c) {}).length); // 120 ??console.log("function(a, b, c = 1)",(function(b, c, a = 1) {}).length); // 221 22 ??//没有默认值:参数个数23 ??console.log("function()",(function(){}).length); /* 0 */24 ??console.log("function(a)",(function(a){}).length); /* 1 */25 ??console.log("function(a, b)",(function(a, b){}).length); /* 2 */26 27 ??// 与之对比的是, ?arguments.length 是函数被调用时实际传参的个数28 ??console.log("fun (1,2,3) :arguments.length",(function(a = 1, b, c) {return arguments.length})(1,2,3)) // 329 30 ??//MDN:Function 构造器本身也是个Function,它的 length 属性值为 131 ??console.log("MDN:Function.length",Function.length); /* 1 */32 33 var length="outter";34 var obj = {35 ??length:"inner",36 ??exec:function (){37 ????return (function(length){38 ??????return function(){39 ????????// code40 ??????}41 ????})(this.length);42 ??}43 };44 45 var exec=obj.exec();46 console.log(exec.length); // 0 47 // 解析: 返回的 exec 是一个闭包 function(){...} ,由上面的 function(){}.length 返回 0 ,可知此处也是返回 048 49 </script>50 </body>51 </html>
JS 中函数的 length 属性
原文地址:https://www.cnblogs.com/go4it/p/9678028.html