【问题标题】:Why do functions have a length property?为什么函数有长度属性?
【发布时间】:2013-07-03 20:41:18
【问题描述】:

我一直在摆弄一些代码here。由于某种原因,函数被检测为 b.c. 的抽象数组。它有一个长度属性。不是主要问题,b.c.它是 0,但我觉得这很奇怪。

var test_set = [null,
                undefined,
                NaN,
                true,
                false,
                1,
                'a',
                {test:'test'},
                [0], 
                function(){}, 
                /test/
               ];

var index, 
    key,
    test;

function isArrayAbstract (obj) {
    return (obj != null) && (obj.length === +obj.length);
};

for(index = 0; index < test_set.length; index++){
    test = isArrayAbstract(test_set[index]);
    console.log('Mark | ' + test_set[index]);
    console.log(test);
}

【问题讨论】:

标签: javascript


【解决方案1】:

Function.length

length 是函数对象的属性,表示函数需要多少个参数,即形式参数的数量。 相比之下,arguments.length 是函数的局部变量,它提供实际传递给函数的参数数量。

查看示例:

console.log( (function () {}).length );  /* 0 */
console.log( (function (a) {}).length ); /* 1 */
console.log( (function (a, b) {}).length ); /* 2 etc. */
console.log( (function (...args) {}).length ); /* 0, rest parameter is not counted */

也请参考ECMAScript Language Specs

本子句中描述的每个内置函数对象——无论是作为构造函数、普通函数还是两者——都有一个长度属性,其值为整数。除非另有说明,否则此值等于函数描述的子条款标题中显示的命名参数的最大数量,包括可选参数。

【讨论】:

    【解决方案2】:

    length 属性指定函数期望的参数数量。

    来自MDN

    length是函数对象的一个​​属性,表示函数需要多少个参数,即形参的个数。

    (function(){}).length;  // 0
    (function(a){}).length; // 1
    

    【讨论】:

    • @pure_code.mom:虽然函数具有.length 属性,但它们没有数字属性。与数组或类数组对象的.length属性不可比,意义不同。
    • @pure_code.mom 这就是arguments 对象的用途。
    【解决方案3】:

    函数的长度属性是它定义为接收的参数的数量。示例

    function foo(a,b){
    ...
    }
    

    在这种情况下 foo.length 将为 2。

    【讨论】:

      【解决方案4】:

      实际上,函数上的length 字段是有目的的。来自MDN documentation for Function.length

      指定函数期望的参数数量。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-05-04
        • 1970-01-01
        • 1970-01-01
        • 2023-04-05
        • 1970-01-01
        • 1970-01-01
        • 2012-12-12
        相关资源
        最近更新 更多