Jquery array like object

I’m writing a simple Dom script and trying to figure out the best approach.

Correct me if I’m wrong but essentially jquery works with an array like object. So for instance if we had a collection of list items the object instance would end up looking a bit like this.

{ 
[0] : htmlElement,
[1] : htmlElement,
[2] : htmlElement,
[3] : htmlElement,
[4] : htmlElement,
length : 5
}

I would be tempted to go with an array instead.

{ elems : [htmlElement, htmlElement, htmlElement, htmlElement, htmlElement]
}

I mean to create our array like object from a htmlcollection for example getElementsByTagName(‘li’) we have to go through something like the following.

A method on the prototype

function(obj) {
var clone = type(obj) === 'array' ? obj : [].slice.call(obj);

clone.unshift(0, clone.length);
[].splice.apply(this, clone);
}

I know that one benefit is that you don’t need an accessor, so you can get to an item with object, but are there any other benefits. The array just seems to me to be easier to work with.

I hope the above makes sense.

Thanks

RLM

The reason why jQuery uses an object is so that they can make other properties and methods accessible from that object as well.

If an array is easier for you to use in your project, then that can be a good solution for you.

The reason why jQuery uses an object is so that they can make other properties and methods accessible from that object as well.

Thanks Paul. I’m being a bit dense here. Can you possibly expand on that? For example?

You can still add other properties and methods to ‘this’.

{
elems: [htmlElement, .....],
otherProp: ...,
otherMethod: ...
}

Sorry if my question opens a whole can of worms. I’m struggling to see the bigger picutre.

RLM

Instead of having the array as a separate elems property, imagine an object that fakes array-like information, including a fake length property:

{
0: ‘item 1’,
1: ‘item 2’,
2: ‘item 3’,
length: 3,
otherProp: …,
otherMethod: …
}

The benefit is that people using it don’t need to know that it is an object. They can still use array indexing and looping on it with no trouble at all.

Okay that makes sense.

So as I’m the end user an array will probably be fine.

Thanks again:)