Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
65
rated 0 times [  67] [ 2]  / answers: 1 / hits: 152251  / 14 Years ago, fri, september 3, 2010, 12:00:00

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?


More From » object

 Answers
6

No, this is not possible. The key will always be converted to a string. See Property Accessor docs




Property names must be strings. This means that non-string objects cannot be used as keys in the object. Any non-string object, including a number, is typecasted into a string via the toString method.




> var foo = {}
undefined

> foo[23213] = 'swag'
'swag'

> foo
{ '23213': 'swag' }

> typeof(Object.keys(foo)[0])
'string'

[#95717] Tuesday, August 31, 2010, 14 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
longd

Total Points: 616
Total Questions: 110
Total Answers: 101

Location: Andorra
Member since Sat, May 27, 2023
1 Year ago
;