当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


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。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。