<注>
那个链接的答案中的实际代码是:
var args = Array.prototype.slice.call(arguments, 1)
首先,slice
方法通常用于复制调用它的数组:
i.e. "slice",而不是"splice"
</Note>
var a = ['a', 'b', 'c'];
var b = a.slice();
var c = a.slice(1);
所以简短的回答是,代码基本上是在模拟:
arguments.slice(1); // discard 1st argument, gimme the rest
然而,你不能直接这样做。
特殊的arguments
对象(在所有JavaScript函数的执行上下文中可用),虽然类似于数组,支持通过数值键使用
[]
运算符进行索引,但实际上并不是一个数组;你不能对其进行
.push
、
.pop
或
.slice
等操作。
代码实现的方法是通过“欺骗”
slice
函数(再次强调,该函数不适用于
arguments
对象)通过
Function.prototype.call
在
arguments
的上下文中运行:
Array.prototype.slice // get a reference to the slice method
// available on all Arrays, then...
.call( // call it, ...
arguments, // making "this" point to arguments inside slice, and...
1 // pass 1 to slice as the first argument
)
Array.prototype.slice.call(arguments).splice(1)
实现了相同的功能,但是会多调用一次splice(1)
,这会导致从Array.prototype.slice.call(arguments)
返回的数组中从索引1
开始到数组末尾的元素被移除。在IE中,splice(1)
无法正常工作(它需要一个第二个参数来告诉它要删除多少项,而IE和ECMAScript都要求提供该参数)。