Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I extend Array.prototype.push()?

I'm trying to extend the Array.push method so that using push will trigger a callback method and then perform the normal array function.

I'm not quite sure how to do this, but here's some code I've been playing with unsuccessfully.

arr = []; arr.push = function(data){      //callback method goes here      this = Array.push(data);     return this.length; }  arr.push('test'); 
like image 423
Geuis Avatar asked Feb 21 '09 07:02

Geuis


People also ask

Can we push function in array?

push() method is used to push one or more values into the array. This method changes the length of the array by the number of elements added to the array. Parameters This method contains as many numbers of parameters as the number of elements to be inserted into the array.

What is array prototype push apply?

Array. prototype. push() is a method that adds one or more elements to the end of the array and returns the new length of the array. Array.

Does push modify an array?

push() adds item(s) to the end of an array and changes the original array. unshift() adds an item(s) to the beginning of an array and changes the original array. splice() changes an array, by adding, removing and inserting elements.

Can we push array into array?

Adding Array into the Array using push() push() method. The push() function allows us to push an array into an array. We can add an array into an array, just like adding an element into the Array.


1 Answers

Since push allows more than one element to be pushed, I use the arguments variable below to let the real push method have all arguments.

This solution only affects the arr variable:

arr.push = function () {     //Do what you want here...     return Array.prototype.push.apply(this, arguments); } 

This solution affects all arrays. I do not recommend that you do that.

Array.prototype.push = (function() {     var original = Array.prototype.push;     return function() {         //Do what you want here.         return original.apply(this, arguments);     }; })(); 
like image 62
some Avatar answered Oct 16 '22 10:10

some