當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


JavaScript Function.length屬性用法及代碼示例


Javascript中函數對象的Function.length屬性用於返回一個函數需要的參數個數。

用法:

function.length

參數:此方法不需要參數。

返回:返回類型是數字。

為了更好地理解該方法,下麵給出了幾個例子。



範例1:

html


<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport"
        content="width=device-width,
                initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <script>
    // Creating function name func
    // When no parameters are given
    function func1(){}
    console.log(
"The number of parameters required by "+
     "the function are:", func1.length)
  </script>
</body>
</html>

輸出:

範例2:

當參數個數大於 1 時。

html


<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport"
        content="width=device-width,
                 initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <script>
    // Creating function name func
    // When one parameters are given
    function func1(a){}
    console.log(
"The number of parameters required by the func1 are:",
  func1.length)
    // When two parameters are given
    function func2(a, b){}
    console.log(
"The number of parameters required by the func2 are:",
 func2.length)
    // When three parameters are given
    function func3(a, b, c){}
    console.log(
"The number of parameters required by the func3 are:",
 func3.length)
    // When four parameters are given
    function func4(a, b, c, d){}
    console.log(
"The number of parameters required by the func4 are:",
 func4.length)
  </script>
</body>
</html>

輸出:

範例3:

當給出參數數組時

html


<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport"
        content="width=device-width,
                 initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <script>
    // Creating function name func
    // When array of arguments are given
    function func4(...args){}
    console.log(
"The number of parameters required by the func4 are:",
 func4.length)
  </script>
</body>
</html>

輸出:




相關用法


注:本文由純淨天空篩選整理自tarun007大神的英文原創作品 JavaScript Function.length property。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。