May 15, 2010

Array in javascript

Technically, array in javascript is not really array in the context of other language like c#, it is more like a dictionary, the index is actually used as a key of an entry in the dictionary, like to the following.

var a = [];
a[0] = "fred";
alert(a["0"] == a[0]);

It is unique in that it has a length property, when you push an new item, array can automatically increase its length. It is also unique in that it support traditional for statement like for (i=1; i< a.length; i++) { ... }. Because Array is also an object so we can also use statement like "for ( var i in x), but it is not recommended because it defeat the purpose of array.



On the other hand, we can simulate the array feature for normal object. jQuery also use the technique like the following, so that jQuery object looks like an object, but it is not.


var push = [].push;
var y = {};
push.call(y, 100);
alert(y.length); //1
alert(y[0]); //100
​

To delete an array, do not use "delete array[index]" use array.splice(index, 1);