<注>
從linked answer的實際代碼:
var args = Array.prototype.slice.call(arguments, 1);
即 「切片」,而不是 「拼接」
< /注>
首先,slice
方法通常用於make a copy of the array it's called on:
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
但是你不能直接這樣做。 special arguments
object(在所有JavaScript函數的執行上下文中可用),儘管它們支持通過帶數字鍵的[]
運算符進行索引,但實際上並不是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要求)。
很抱歉的代碼差了,但我複製我在這裏粘貼代碼http://stackoverflow.com/questions/373157/how-我可以通過在這個問題中鏈接到的答案來傳遞參數到函數的參數,但作者在此期間更改了腳本。再次,對此表示歉意 – 2009-11-22 03:54:27
@Andreas:檢查mah updatez – 2009-11-22 03:55:20
很好的答案! +1 – 2009-11-22 04:05:24