Javascript'参数'关键字

Kev*_*ith 7 javascript

我的理解是我可以调用Array.prototype.slice.call(arguments, 1)返回数组的尾部.

为什么这段代码不会返回[2,3,4,5]

function foo() {  
    return Array.prototype.slice.call(arguments,1);
}

alert(foo([1,2,3,4,5]));
Run Code Online (Sandbox Code Playgroud)

Nie*_*sol 13

arguments是一个类似于数组的对象,它列出了参数和一些其他属性(例如对当前函数的引用arguments.callee).

在这种情况下,您的arguments对象如下所示:

arguments {
    0: [1,2,3,4,5],
    length: 1,
    other properties here
}
Run Code Online (Sandbox Code Playgroud)

我认为这可以解释你所看到的行为.尝试删除函数调用中的数组括号,或使用arguments[0]访问arry.


Poi*_*nty 11

因为你只传递一个参数 - 数组.

尝试 alert(foo(1,2,3,4,5));

参数在JavaScript中从0开始编号,因此当您从1开始切片并传递1个参数时,您什么都得不到.

请注意,它可能会妨碍优化,以允许arguments对象"泄漏"出函数.由于arguments和形式参数之间存在别名,如果arguments对象被发送到其他地方,优化器就无法对函数进行任何静态分析,因为它不知道参数变量会发生什么.