The following two different code snippets seem equivalent to me:
var myArray = Array();
myArray['A'] = "Athens";
myArray['B'] = "Berlin";
and
var myObject = {'A': 'Athens', 'B':'Berlin'};
because they both behave the same, and also typeof(myArray) == typeof(myObjects)
(both yield 'object').
Is there any difference between these variants?
Virtually everything in javascript is an object, so you can "abuse" an Array object by setting arbitrary properties on it. This should be considered harmful though. Arrays are for numerically indexed data - for non-numeric keys, use an Object.
Here's a more concrete example why non-numeric keys don't "fit" an Array:
var myArray = Array();
myArray['A'] = "Athens";
myArray['B'] = "Berlin";
alert(myArray.length);
This won't display '2', but '0' - effectively, no elements have been added to the array, just some new properties added to the array object.
myArray.length returns a numeric index/key of the last element in array but not the actual number of elements. Are properties of the Array object not the same as array values?
I was just trying to illustrate the intended semantics of the Array object are abused if you just treat it like a regular object. The linked article does a better job though :)
The next time someone says JavaScript is a good language to develop with, I'll show him this sample. Thank you.
@Olivier, what you call a "bug" can as well be an awesome "feature". You can add a tittle and description to arrays without affecting their contents or length and without having to wrap them in objects with
title
,description
anditems
properties. It all depends on how well you know the language and how you use it.Using custom properties on Arrays is not inherently wrong. What's wrong is expecting them to act as array members once you do. They are array properties, not members, hence not affected by array methods. This is actually said by the author of the above linked article, in the comments. Now, in all fairness, I would advise against it as a practice, as it will probably confuse the hell out of people using your code. Or, if they're just starting, it will set them on a dangerous path, by power of example. But I wouldn't say JavaScript is bad because it allows stuff most don't expect to be allowed.