Reputation: 199
I'm reading JavaScript:The Good Parts by Crockford and I'm having trouble understanding the reimplementation of the unshift
method that he does in his book.Here is the the code:
Array.method('unshift', function ( ) {
this.splice.apply(this,
[0, 0].concat(Array.prototype.slice.apply(arguments)));
return this.length;
});
It would be useful if someone could go through what is happening step by step. One of the things that I don't understand is why he concatenates [0 , 0] to the result of the Array.prototype.slice
.
Upvotes: 1
Views: 156
Reputation: 944175
why he concatenates [0 , 0] to the result of the Array.prototype.slice
The first two arguments of splice
(which is where the resulting array is applied to) are:
index
which is 0
because you are adding to the front of the arrayhowMany
(to remove) which is 0
because you are just adding new elementsThe remaining arguments are the values to be added to the front of the array, which are taken from Array.prototype.slice.apply(arguments)
(to convert the data into the arguments
object into data in an array).
Upvotes: 5