<注意>
该链接答案的实际代码是:
var args = Array.prototype.slice.call(arguments, 1);
即“切片”,而不是“拼接”
</Note>
首先,该slice
方法通常用于制作它所调用的数组的副本:
var a = ['a', 'b', 'c'];
var b = a.slice(); // b is now a copy of a
var c = a.slice(1); // c is now ['b', 'c']
所以简短的回答是代码基本上是在模拟:
arguments.slice(1); // discard 1st argument, gimme the rest
但是,您不能直接这样做。特殊arguments
对象(在所有 JavaScript 函数的执行上下文中可用)虽然类似于Array ,因为它支持通过[]
带有数字键的运算符进行索引,但实际上并不是 Array;你不能.push
上它,.pop
下它,或.slice
它,等等。
代码实现这一点的方式是通过“欺骗”函数(在对象slice
上再次不可用)在 的上下文中运行,通过:arguments
arguments
Function.prototype.call
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
并继续到数组的末尾。splice(1)
在 IE 中不起作用(从技术上讲,它缺少第二个参数,告诉它删除 IE 和 ECMAScript 需要多少项)。