Possible Duplicate:
Array-like object in javascript
Javascript has native objects that are array-like objects (eg. arguments, NodeList).
I would like to know:
- What are the advantages of creating an array-like object?
- When should be a good idea to create an array-like object (rather than create a regular array object)?
You’re looking at it from the wrong side: the early versions of Java(Live)Script didn’t have arrays, only objects. An array, in fact, is an augmented objects (indeces are converted to strings internally!). So an Array is an Object, like
argumentsis an object… there are some overlaps, some differences…To answer your question: you can never really make an
argumentsobject, that’s just inherent to functions and you should treat them as read-only objects.NodeLists are objects, returned by stuff like
document.getElementsByTagName('a');, the advantage of them is that (except for IE, of course) they come with a couple of neat methods:So when should you use what? Well, dealing with nodes: 9 times out of 10 you’re best served with a nodes list, arguments objects are what you need inside functions. Since JS is a functional language, you need them a lot.
That said, it really doesn’t matter that much: chances are you’ve come across code like this:
This just borrows the slice method from the Array prototype and calls it as if it were a method of the arguments object.
That’s all there is to say, really. There is no definitive answer here, just that old mantra: go with your gut feeling. Try, fail, learn and try again.
Just know that, whatever you do, you can borrow prototype (or even instance) methods, and that everything traces back to the mother Object.prototype prototype.