JS 中函數的 length 屬性
阿新 • • 發佈:2018-09-20
數量 class 多少 調用 charset () ole pan ner
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); // 0 15 16 //有默認值:包括第一個具有默認值之前的參數個數 17 console.log("function()",function(){}.length); // 0 18 console.log("function(a = 1, b, c)",(function(a = 1, b, c) {}).length); // 0 19console.log("function(a, b = 1, c)",(function(b, a = 1, c) {}).length); // 1 20 console.log("function(a, b, c = 1)",(function(b, c, a = 1) {}).length); // 2 21 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)) // 3 29 30 //MDN:Function 構造器本身也是個Function,它的 length 屬性值為 1 31 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 // code 40 } 41 })(this.length); 42 } 43 }; 44 45 var exec=obj.exec(); 46 console.log(exec.length); // 0 47 // 解析: 返回的 exec 是一個閉包 function(){...} ,由上面的 function(){}.length 返回 0 ,可知此處也是返回 0 48 49 </script> 50 </body> 51 </html>
JS 中函數的 length 屬性