OK.
How do I append to an array in Javascript?
Update : actually
a.push(b)
does work. Realize that my previous problem was b not having a value.
Ok, I answered myself, but might as well leave this here on SO to help other newbies.
OK.
How do I append to an array in Javascript?
Update : actually
a.push(b)
does work. Realize that my previous problem was b not having a value.
Ok, I answered myself, but might as well leave this here on SO to help other newbies.
var arr = new Array(3);
arr[0] = "Hi";
arr[1] = "Hello";
arr[2] = "Bonjour";
arr.push("Hola");
for (var i = 0; i < arr.length; i++) {
alert(arr[i]);
};
If you're only appending a single variable, than your method works just fine. If you need to append another array, use concat(...) method of the array class:
var ar1 = [1, 2, 3];
var ar2 = [4, 5, 6];
var ar3 = ar1.concat(ar2);
alert(ar3);
Will spit out "1,2,3,4,5,6"
Lots of great info here
Some quick benchmarking (each test = 500k appended elements and the results are averages of multiple runs) showed the following:
Firefox 3.6 (Mac):
arr[arr.length] = b
is faster (300ms vs. 800ms)arr.push(b)
is faster (500ms vs. 900ms)Safari 5.0 (Mac):
arr[arr.length] = b
is faster (90ms vs. 115ms)arr[arr.length] = b
is faster (160ms vs. 185ms)Google Chrome 6.0 (Mac):
I like the arr.push()
syntax better, but I think for my use I'd be better off with the arr[arr.length]
version, at least in raw speed. I'd love to see the results of an IE run though.
My benchmarking loops:
function arrpush_small() {
var arr1 = [];
for (a=0;a<100;a++)
{
arr1 = [];
for (i=0;i<5000;i++)
{
arr1.push('elem'+i);
}
}
}
function arrlen_small() {
var arr2 = [];
for (b=0;b<100;b++)
{
arr2 = [];
for (j=0;j<5000;j++)
{
arr2[arr2.length] = 'elem'+j;
}
}
}
function arrpush_large() {
var arr1 = [];
for (i=0;i<500000;i++)
{
arr1.push('elem'+i);
}
}
function arrlen_large() {
var arr2 = [];
for (j=0;j<500000;j++)
{
arr2[arr2.length] = 'elem'+j;
}
}