arguments的介绍(一)

arguments 是一个类数组对象。代表传给一个function的参数列表。

1.1 arguments length

arguments 是个类数组对象,其包含一个 length 属性,可以用 arguments.length 来获得传入函数的参数个数。

 

function func() {
    console.log("The number of parameters is " + arguments.length);
}

func();
func(1, 2);
func(1, 2, 3);

执行结果如下:

The number of parameters is 0
The number of parameters is 2
The number of parameters is 3

1.2 arguments 转数组

通常使用下面的方法来将 arguments 转换成数组:

Array.prototype.slice.call(arguments);
[].slice.call(arguments);

1.3 leaking arguments

另外,有一个需要注意的地方就是,不能将函数的 arguments 泄露或者传递出去。什么意思呢?看下面的几个泄露 arguments 的例子:

// Leaking arguments example1:
function getArgs() {
    return arguments;
}

// Leaking arguments example2:
function getArgs() {
    const args = [].slice.call(arguments);
    return args;
}

// Leaking arguments example3:
function getArgs() {
    const args = arguments;
    return function() {
        return args;
    };
}

上面的做法就直接将函数的 arguments 对象泄露出去了,最终的结果就是 V8 引擎将会跳过优化,导致相当大的性能损失。

可以这样做:

function getArgs3 () {
    const args = new Array(arguments.length)
    for (let i = 0; i < args.length; i++) {
    args[i] = arguments[i]
    }
    return args;
}

1.4 修改arguments的值

   // 修改arguments的值
    function foo(a) {
        "use strict";
        console.log(a, arguments[0]); // 1  1
        a = 10;
        console.log(a, arguments[0]); // 10 1
        arguments[0] = 20;
        console.log(a, arguments[0]); // 10 20
    }
    foo(1);
    function bar(a) {
       console.log('-----非严格模式下的值变化------')
        console.log(a, arguments[0]); // 1 1
        a = 10;
        console.log(a, arguments[0]); // 10 10
        arguments[0] = 20;
        console.log(a, arguments[0]); // 20 20
    }
    bar(1);

从上面的两个例子中可以看出,在严格模式下,函数中的参数与 arguments 对象没有联系,修改一个值不会改变另一个值。而在非严格模式下,两个会互相影响。

原文地址:https://www.cnblogs.com/xuzhudong/p/10254797.html