I typed the following into the chrome console:
> Array.prototype.slice.call([1,2], 0)
[1, 2]
> Array.prototype.slice.call([1,2], 1)
[2]
Why does the first call not return 1?
I typed the following into the chrome console:
> Array.prototype.slice.call([1,2], 0)
[1, 2]
> Array.prototype.slice.call([1,2], 1)
[2]
Why does the first call not return 1?
Slice with one argument returns the array from the index position you give in the argument. In your case 0 marks the index position 0, so it returns the whole array.
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
The second argument would be how many element it slices out starting from index, so:
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)
returns all elements of the array starting from index 0, and puts the whole into the array.
Array.prototype.slice.call([1,2], 1)
returns all elements of the array starting from index 1, and puts the whole into the array, however this time it finds only 1 element, the 2
.
As indicated here, the slice
method accepts a start and optionally an end offset, not the index of the element to slice out. If no offset is provided, it will slice to the end of the array.
In your first example, slice
starts from element 0, while in the second example it starts from element 1. In both occassions it will any elements it can find at that index and after, since you have not specified an offset.
First parameter to slice is the start index in the array (counting from zero). The second parameter (which is not given in either of your examples), is the end. Precisely it is: one past the inclusive end index. Anyway, it defaults to the end of the array, which is the behaviour you see.
Array.prototype.slice.call([1,2], 0, 1)
should give you [1]
slice.call(arguments, Fromindex);
The Fromindex means to slice the arguments list from index to the end.
as your case slice the arguments from index 1
thats why you get [2]