pradeep79 Posted April 14, 2007 Share Posted April 14, 2007 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? Quote Link to comment https://forums.phpfreaks.com/topic/46946-javascript-shift-not-working/ Share on other sites More sharing options...
MadTechie Posted April 14, 2007 Share Posted April 14, 2007 wrong section! Quote Link to comment https://forums.phpfreaks.com/topic/46946-javascript-shift-not-working/#findComment-228935 Share on other sites More sharing options...
Glyde Posted April 14, 2007 Share Posted April 14, 2007 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; } Quote Link to comment https://forums.phpfreaks.com/topic/46946-javascript-shift-not-working/#findComment-228954 Share on other sites More sharing options...
pradeep79 Posted April 14, 2007 Author Share Posted April 14, 2007 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... Quote Link to comment https://forums.phpfreaks.com/topic/46946-javascript-shift-not-working/#findComment-229006 Share on other sites More sharing options...
Glyde Posted April 14, 2007 Share Posted April 14, 2007 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. Quote Link to comment https://forums.phpfreaks.com/topic/46946-javascript-shift-not-working/#findComment-229055 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.