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;
}

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...

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.

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.