ABC said:
... I was wondering if someone could tell me what
the code below is doing.
The function creates a new Array and assigns it to a property of an
object (global) called - aKey - . Which is probably an Array itself as
it is indexed with the (global) variable - nbrKeys - which is probably a
number (integer) as it is subject to mathematical (post increment)
operations.
The function then creates a number of named properties of the array and
assigns values to them. JavaScript Arrays are objects (with extra
functionality added) and can have named properties added to them at any
point. Finally a value is assigned to the array element at index 0 and
the - nbrKeys - variable in incremented.
Is it creating a multidimensional array?
Not really. JavaScritp does not do multidimensional arrays as such, it
can do Arrays of Arrays (which is similar, even practically identical in
some cases). Assuming that - aKey - is an Array to start with assigning
an Array to one of its elements will make it an Array of Arrays (but
values assigned elsewhere in the code cannot be determined form this
function example so the - aKey - array may contain references to any
objects of any type and any primitive values in its other elements).
Would it be better to create an object?
<snip>
Impossible to say from just this code. As it is the new Array assigned
as an indexed element of - aKey - is having values assigned to its
indexed elements so it is possible that its Array-ness is being
exploited elsewhere in the code and an Array is the appropriate object
to be using.
Generally, if you want Array-like behaviour (indexing by integer) then
an Array is the appropriate object to use. If you want to index by name
only then a plain object would usually be better and if you want to do
both (as in this example) then you have a range of choices including
exploiting the Object-ness of an Array to provide named properties.
Richard.