Jump to content

Javascript shift() not working


pradeep79

Recommended Posts

I believe javascript does not have a shift function by default.  Here is one (use as you did above, i.e. a.shift()):

Array.prototype.shift = function() {
     returnValue = this[0];
     for (var i = 0; i < this.length - 1; i++)
          this[i] = this[i + 1];
     this.length--;
     return returnValue;
}

Link to comment
Share on other sites

Thanks for that, where do i put that bit of javascript in my code? I have tried similar prototypes and weird my browser still says it is not a function. After 8 hours of breaking my head with this trivial bit of code, I thought of implementing the shift myself, it works(not as a prototype thought). Now trying to figure out how to implement push(), coz that doesn't seem to be there as well...Help me if you got any more ideas. Thanks again for ur reply...

Link to comment
Share on other sites

Push is there.  Ensure that you are creating your arrays with the new Array() syntax, as I'm not entirely sure that using the shorthand [] syntax will inherit the prototype methods.  Also, if you're trying to use the arguments array, you'll need this:

var $A = function(src) {
     tmpArray = new Array()'
     for (var i = 0; i < src.length; i++)
          tmpArray.push(src[i]);
     return tmpArray;
}

 

Then you can call something like:

var a = $A(arguments);
firstArg = a.shift();
secondArg = a.shift();

 

Put these functions before anything else in your code so they are easy to find and will always be defined.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.