Is there a way to use a numeric type as an object key?

It seems that when I use a numeric type as the key name in an object, it always converts to a string. Is there anyway to actually make him keep a digit? Normal type conversion does not work.

Example:

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

Output signal:

 { '1': 'a value' } 

What I want :

 { 1: 'a value' } 

Tip

thank

+41
javascript object types numeric key
03 Sep '10 at 5:58
source share
4 answers

No, It is Immpossible. The key will always be converted to a string. See Access 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 entered into the string through the toString method.

 > var foo = {} undefined > foo[23213] = 'swag' 'swag' > foo { '23213': 'swag' } > typeof(Object.keys(foo)[0]) 'string' 
+45
03 Sep 2018-10-10T00:
source share

Design appears in ECMA-262-5:

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

However, I do not see a specific specification in ECMA-262-3. Regardless, I would not use non-strings as property names.

+7
Sep 03 '10 at 7:08
source share

There is no object, but I found Map extremely useful for this application. Here I used it for numeric keys, key based events.

 onKeydown(e) { const { toggleSidebar, next, previous } = this.props; const keyMapping = new Map([ [ 83, toggleSidebar ], // user presses the s button [ 37, next ], // user presses the right arrow [ 39, previous ] // user presses the left arrow ]); if (keyMapping.has(e.which)) { e.preventDefault(); keyMapping.get(e.which)(); } } 
+7
May 31 '16 at 16:46
source share

In JavaScript, numeric strings and numbers are interchangeable, so

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

If you really want the number to be the key for the object, you may need an array (that is, created using new Array() or [] ).

-3
Sep 03 '10 at 6:02
source share



All Articles