0

Possible Duplicate:
Array-like object in javascript

Javascript has native objects that are array-like objects (eg. arguments, NodeList).

I would like to know:

  1. What are the advantages of creating an array-like object?
  2. When should be a good idea to create an array-like object (rather than create a regular array object)?
0

1 Answer 1

1

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 arguments is an object... there are some overlaps, some differences...

To answer your question: you can never really make an arguments object, 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:

var inputs = document.getElementsByTagName('input');
var userNameIn = inputs.namedItem('username');//Arrays don't have this

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:

var myArgs = Array.prototype.slice.apply(arguments,[0]);

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.

Sign up to request clarification or add additional context in comments.

2 Comments

My question is "when should I create my own array-like class/object" and is there benefit?
Well, I gather you mean object literal when you say "array-like object". There are benefits (lots): assigning methods, pass through ajax calls and parse as assoc array... it's really what JS is all about, IMO so when should you use it? whenever the data is going to be sent either to a function or the server.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.