views:

42

answers:

3

It seems that when I use a numeric type as a key name in an object, it always gets converted to a string. Is there anyway to actually get it to store as a numeric? The normal typecasting does not seem to work.

Example:

var userId = 1;
console.log( typeof userId ); // number
myObject[userId] = 'a value';
console.dir(myObject);

Dir Output:

{
    '1': 'a value'
}

What I want is this:

{
    1: 'a value'
}

Advice?

Thanks

A: 

In JavaScript, numerical strings and numbers are interchangeable, so

myObject[1] == myObject['1']

If you really want number to be the key for an object, you might want an array (i.e. created with new Array() or []).

William
Thanks for the response but this is not entirely accurate. A numeric will only return as 'number' from a typeof, and vice versa with a string.
Spot
+2  A: 

No, this is not possible. It will always be converted to a string. This is done in step 6 of the ECMAScript Property Accessor (§11.2.1) algorithm.

Matthew Flaschen
Thank you. Is this considered a flaw in the language, or is it accepted as a good design decision?
Spot
That's rather subjective. As William noted, for integer keys you can instead use an array. Most JS engines can use sparse arrays behind the scenes.
Matthew Flaschen
Even in an array, all property names are converted to strings.
Tim Down
A: 

Appears to be by design in ECMA-262-5:

The Property Identifier type is used to associate a property name with a Property Descriptor. Values of the Property Identifier type are pairs of the form (name, descriptor), where name is a String and descriptor is a Property Descriptor value.

However, I don't see a definite specification for it in ECMA-262-3. Regardless, I wouldn't attempt to use non-strings as property names.

Rob Olmos