0

I've never worked with prototype, and maybe I don't even understand how it works, so here I am.

I'm trying to change how .push() works in javascript: it adds the parameter as the last element, but I want it to add the parameter in the first position.

Here is my non-working guess:

    Array.prototype.push() = function(e){
      var x = [e]; 
      return x.concat(this);
    }

Sorry for the breathtaking mistakes I probably made :)

Disclaimer: I'm just trying to understand how to modify native methods. Why is everybody so scared?

9
  • The built-in .unshift() method adds new elements to the start of the array - any reason why you're not using it instead of trying to redefine .push()? Commented Jun 10, 2017 at 7:50
  • push does not remove last element in the array, it adds new one to the array Commented Jun 10, 2017 at 7:50
  • Thanks for your answers. I wanted to say add, not remove. I wasnt focused. Commented Jun 10, 2017 at 7:54
  • Regarding your edit, now you say you want it to add the parameter in "the last position", but that's what .push() already does (at least, it doesn't overwrite whatever is already in the last position, it appends after it, but...). Commented Jun 10, 2017 at 7:54
  • o man i need to sleep more haha sorry. Commented Jun 10, 2017 at 7:56

2 Answers 2

1

Just loose the parenthesis :

Array.prototype.push = function(e){
  var x = [e]; 
  this.unshift(e);
}

EDIT:

If you don't want to use unshift inside, you can do splice :

 Array.prototype.push = function(e){
   var x = [e];   
var y = [];
   for(var j = 0; j< this.length; j++) y[j] = this[j];
   this[0] = x;
   for(var i = 0; i < y.length; i++) this[i+1] = y[i];
}
Sign up to request clarification or add additional context in comments.

11 Comments

I don't think all browsers support overriding native functions.
@Prajwal Well, I don't think so. Can you please give an example of browser?
This code will return a new array rather than modifying the array it is called on.
@binariedM thank but i cant make it work. The console says: "Uncaught ReferenceError: Invalid left-hand side in assignment" in the line of "this = x.concat..."
You don't need the temporary y array, you can slide the existing elements to the right with one loop something like for(var i = this.length; i > 0; i--) this[i] = this[i-1]. (With a slight adjustment you can slide the elements over by more than one space, should you want to insert multiple elements at the beginning.)
|
1

To add element in first position use .unshift. You don't need prototype for this.

You don't want to override .push() or any other native method.

var data = [1,2,3,4,5];
data.unshift(10);

// 10 is first element
console.log(data);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.