I know this is an old post, but since I found it anyone else might as well, so I'll just correct some of the mistakes I noticed.
Both the shift and unshift methods are flawed.
If we'd do the unshift method as shown here, we'd get the following:
say we want to add 1 to the array [2,3,4,5].
As the method suggests, we start with i=1 -> we copy number 2 from position 0 to 1;
next iteration i=2 -> there is number 2 on position 1 from last iteration, so we copy number 2 from position 1 to 2;
by now you already get the picture - in each iteration we copy the number 2 (or whatever you had on position 0 at the beginning) one position higher. After adding number 1 on the 0th position, we get the final array [1,2,2,2,2], which is now what we wanted.
here is a possible fix to that:
this[this.length] = null;/* create a new last element */
this[i] = this[i-1]; /* shift elements upwards */
this = item;
This will start coping items from the higher end and thus keeping the array and making room for the new first element.
As for the shift method - it doesn't return anything, although the description said it would return the first element of an array. Solution:
var t = this;
this[i-1] = this[i] /* shift element downwards */
this.length = this.length-1;
I anyone notices anything wrong with my fixes, go ahead and correct me - after all we're here to do thing the right way