If I wanted to write the pop function from scratch what would be the most efficient way? The main issue also is how do I return the originating array without the popped element?
Array.prototype.pop = function () {
var myArray = this;
var length = myArray.length;
var element = myArray[length-1];
myArray = myArray.slice(0,length-1);
return element;
}
var hello = [1,2,3,4,5];
hello.pop();
5
console.log(hello)
[1, 2, 3, 4, 5]
-
so you want a polyfill for pop? returning the last element, and changing your array?hereandnow78– hereandnow782014年02月27日 21:57:44 +00:00Commented Feb 27, 2014 at 21:57
-
"most efficient way" : see the jsperf answer, the one I put is fastest possible polyfill (still 10x slower :P ). I assume this is just for learningAndrew Templeton– Andrew Templeton2014年02月27日 23:21:32 +00:00Commented Feb 27, 2014 at 23:21
4 Answers 4
Use splice instead of slice - slice doesn't modify the original array, whereas splice does.
That said, since you're removing the last element, it would be return myArray.splice(length-1,1);... which is essentially an alias for return myArray.pop() in the first place.
Alternatively, try:
var element = myArray[length-1];
myArray.length = length-1;
return element;
1 Comment
Short and sweet:
Array.prototype.foo = function(){
return this.splice(this.length-1)[0];
};
Returns last element or undefined if zero length and modifies the array itself.
Comments
Ahh performance... Why do you need that polyfill? Array.prototype.pop is widely supportet!
Anyways I created a little perf test to check that: http://jsperf.com/manual-pop
1 Comment
Array.prototype.pop=Array.prototype.pop||function(){
const len = this.length;
const itemToBePopped=this[len-1];
this.splice(len-1,1);
return itemToBePopped;
}