1

Possible Duplicate:
javascript array associative AND indexed?

I am returning an array from a function and am wondering if I can have both a string association and numerical associations as well.

Ex:

array[0] = green;
array[1] = blue;
array['what'] = colors;
Community
  • 1
  • 1
Henry Winn
  • 45
  • 1
  • 1
  • 5

2 Answers2

0

In some way yes, because it's some type of Object. But it's wrong use of them :) Use objects ({}) for named (stringish) indexes and arrays([]) for number indexes.

Setthase
  • 13,988
  • 2
  • 27
  • 30
  • There are some uses for this. Sometimes you just want to carry along some additional data on the Array object. –  Jul 30 '12 at 22:47
  • In some special uses of course, you can mix them, but it can confuse other user of your script. – Setthase Jul 30 '12 at 22:54
0

Arrays are just objects with a special length property and some handy inhertited methods. Since arrays are objects, their property names are strings however the numeric ones ('0','1','2', etc.) are visited by array methods whereas non–numeric ones (e.g. length) aren't. Also, many array methods are generic and can be applied to any object with suitable properties (i.e. a numeric length property and some numeric property names).

Note that to be considered an index, the property name must satisfy the rules for index names so:

var x = [];
x['00'] = '00';  // length = zero as '00' is not an index
x['0']  = '0';   // length = 1 as '0' is an index

It's generally considered bad form to use an array where a plain object will do, though there are no consequences for doing so other than if you mess with the length property.

RobG
  • 142,382
  • 31
  • 172
  • 209