Jump to content

Archived

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

pradeep79

Javascript shift() not working

Recommended Posts

Hi all, I tried to use the javascript shift function and the browser console shows shift is not a function.

 

code:

x=a.shift();

 

My browser is firefox - latest version. Do I have to implement these fuctions myself? Does js have these inbuilt?

Share this post


Link to post
Share on other sites

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

Share this post


Link to post
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...

Share this post


Link to post
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.

Share this post


Link to post
Share on other sites

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