PDA

View Full Version : Equivalent of array.push() in JavaScript?


WA
10-29-2002, 11:10 PM
Just wondering, is there another way of dynamically incrementing an array, without using array.push()? I'm concerned about browser compatibility, and array.push() is a JavaScript1.2 specific feature. In psuedo code, I guess what I'm asking is something like:

array[++]="latest array content"

Thanks,

jkd
10-29-2002, 11:35 PM
Array.prototype.myPush = function() {
for (var i = 0; i < arguments.length; i++)
this[this.length] = arguments[i];

return this.length;
}


Duplicates what is said here:
http://devedge.netscape.com/library/manuals/2000/javascript/1.5/reference/array.html#1196550

WA
10-29-2002, 11:47 PM
Cool. Thanks Jason. Why didn't I think of that code? :D

WA
10-30-2002, 12:42 AM
Just for those following, here's the standard code for simulating array.push(), one that should work in all browsers:


var myarray=new Array()
myarray[myarray.length]="Latest array content"

Apparently array.push() only works in IE5.5+ and NS4+.

Spookster
10-30-2002, 05:06 AM
Originally posted by WA
Just for those following, here's the standard code for simulating array.push(), one that should work in all browsers:


var myarray=new Array()
myarray[myarray.length]="Latest array content"

Apparently array.push() only works in IE5.5+ and NS4+.

Shouldn't that be?


var myarray=new Array()
myarray[myarray.length-1]="Latest array content"


The length gives you the number of elements in the array so if you have 10 elements it will return 10. Your array index numbers will be 0-9.

joh6nn
10-30-2002, 05:12 AM
right, but you want to add a new element to the end of the array, not replace the last element. lenght-1 will return the number of the last element. length by itself will add a new indice to the end.

WA
10-30-2002, 12:11 PM
Yep, John and I are right :) You want to perserve the very last element, so myarray.length should be used.

joh6nn
10-30-2002, 05:25 PM
i came up with the following a while back, when i needed to use them, but was worried about having their availability cross browser. They're untested ( since i don't have a browser that doesn't already support them ), but if someone sees a problem, let me know.

if (!Array.prototype.shift) {
Array.prototype.shift = function() {
var temp = this[0];
this = this.slice(1);
return temp;
}

if (!Array.prototype.unshift) {
Array.prototype.unshift = function() {
var temp = new Array();
temp.concat(arguments, this);
this = temp.slice(0);
return this.length;
}


if (!Array.prototype.pop) {
Array.prototype.pop = function() {
var temp = this[this.length-1];
this.length--;
return temp;
}

if (!Array.prototype.push) {
Array.prototype.push = function() {
this.concat(arguments);
return this.length;
}

WA
10-30-2002, 10:38 PM
Interesting functions joh6nn. I haven't test them out, though may later.