我鍵入以下到鉻控制檯:令人費解的JavaScript行爲
> Array.prototype.slice.call([1,2], 0)
[1, 2]
> Array.prototype.slice.call([1,2], 1)
[2]
爲什麼第一次調用不會返回1?
我鍵入以下到鉻控制檯:令人費解的JavaScript行爲
> Array.prototype.slice.call([1,2], 0)
[1, 2]
> Array.prototype.slice.call([1,2], 1)
[2]
爲什麼第一次調用不會返回1?
如所指出的here,所述slice
方法接受開始和任選的末端偏移,而不是元素的索引切出。如果沒有提供偏移量,它將切片到數組的末尾。從元素0
在你的第一個例子,slice
開始,而在第二個例子中從元素1開始在這兩個occassions將任何元素,它可以找到該索引之後,因爲你還沒有指定的偏移量。
切片第一個參數是所述陣列(從零計數)在開始索引。 第二個參數(在任何一個例子中都沒有給出)是結束。確切地說,它是:通過包容性終端指數。無論如何,它默認爲數組的末尾,這是你看到的行爲。
Array.prototype.slice.call([1,2], 0, 1)
應該給你[1]
切片用一個參數返回從你的論點給索引位置的數組。在你的情況下,0標記索引位置0,所以它返回整個數組。
Array.prototype.slice.call([1,2,3,4,5], 0)
//=> [1,2,3,4,5] because index to start is 0
Array.prototype.slice.call([1,2,3,4,5], 2)
//=> [3,4,5] because index to start is 2
的第二個參數是它多少元件切片出從索引開始,所以:
Array.prototype.slice.call([1,2,3,4,5], 0, 1)
//=> [1] because index to start is 0 and number of elements to slice is 1
Array.prototype.slice.call([1,2,3,4,5], 2, 2)
//=> [3,4] because index to start is 2 and number of elements to slice is 2
Array.prototype.slice.call([1,2], 0)
返回數組的所有元素從索引0,並提出開始整個進入陣列。
Array.prototype.slice.call([1,2], 1)
返回從索引1開始的所有數組元素,並將整個數組放入數組中,但是這次它只找到1個元素2
。
slice.call(arguments,Fromindex);
的的fromIndex裝置從索引參數列表片到最後。
爲你的情況 片從指標參數1
這就是爲什麼你[2]
爲什麼要返回1? – kakarukeys 2012-07-11 06:24:01
你或許應該這樣說的:https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/slice – 2012-07-11 06:24:26
http://stackoverflow.com/questions/2125714/explanation-of-slice-call-in -javascript 可能會提供一個答案。 – cyclops 2012-07-11 06:26:09