The Bear
The Bear

Reputation: 199

JavaScript the Good Parts: unshift function

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

Answers (1)

Quentin
Quentin

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 array
  • howMany (to remove) which is 0 because you are just adding new elements

The 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

Related Questions