javascript associative arrays

J

jor

i want the key of a hash to be based on a variable:

i tried:

var c = 'blah';
var arr = { 'a':1000, b:2000, c.valueOf():3000 };


also
var arr = { 'a':1000, b:2000, c.toString():3000 };

why not?

it seems none of this is allowed.

is there a way to do this?
 
P

Peter Michaux

i want the key of a hash to be based on a variable:

i tried:

var c = 'blah';
var arr = { 'a':1000, b:2000, c.valueOf():3000 };

also
var arr = { 'a':1000, b:2000, c.toString():3000 };

why not?

The PropertyName "keys" in an object literal can only be Identifier,
StringLiteral, or NumericLiteral. This is described in section 11.1.5
of the ECMAScript 3rd ed standard. Follow the link on the group FAQ to
get to the standard

it seems none of this is allowed.

is there a way to do this?

var arr = {};
arr['a'] = 1000;
arr.b = 2000;
arr[c] = 3000;

Peter
 
T

Thomas 'PointedEars' Lahn

Peter said:
var arr = {};
arr['a'] = 1000;
arr.b = 2000;
arr[c] = 3000;

It should be pointed out (to the OP) that despite the chosen identifier
`arr', the referenced object is _not_ an "associative array" or a "hash" as
ECMAScript implementations at least until Edition 3 have no built-in concept
of this. `arr' refers to an Object object with user-defined properties.
`[...]' and `.' merely denote property accesses. `a', `b' and the value of
c are _not_ "keys", but they are property names.


PointedEars
 
T

Thomas 'PointedEars' Lahn

VK said:
is there a way to do this?
var arr = {};
arr['a'] = 1000;
arr.b = 2000;
arr[c] = 3000;

Or even
arr[f()] = 4000;
given that f is a function returning a valid PropertyName

Regarding syntax, f() does _not_ need to return a valid PropertyName as it
already fulfills the condition for the bracket property accessor syntax of
being an Expression, specifically a CallExpression produced with a
MemberExpression followed by what can be produced with the Arguments production.

Regarding *functionality* though, it would have to return something that can
be produced with PropertyName for any reasonable property access because
there can only be property names that can be produced by that production.

However, as both the PropertyName production produces either an Identifier,
a StringLiteral or a NumericLiteral, and any return value is, if not already
a string, type-converted to String on property access, it can be anything
that the syntax for `return' allows, which is actually anything in the end.


PointedEars
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,764
Messages
2,569,567
Members
45,041
Latest member
RomeoFarnh

Latest Threads

Top