Mar 5, 2010

jQuery is an array like object

In javascript, array is object, so there are lots benefit to use array object, like the length, index, slice. jQuery is a collection of element, so use it as an array is very convenient. it seems to me that jQuery object can not use array as prototype for some reason, so how we can use an object like an array, please read the following code.

var x = {};
x[0] = "zero";
x[1] = "one"

var array =, 0 );
alert(array .length); //0
alert(x.length); //undefined
alert(x instanceof Array); //x is not an array, "zero overwritten");
alert(x[0]); //zero x
alert(x[1]); //one
alert(x.length); //now looks like an array, but the it is till 1

array =, 0 );
alert(array .length); //1, "one overwritten");
alert(x[1]); //one x
alert(x.length); //2, length is determine how many elements your push

array =, 0 );
alert(array .length); //2